package com.vca.service.service.Impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vca.common.constants.*;
import com.vca.common.exception.ExceptionCodeEnum;
import com.vca.common.exception.VcaException;
import com.vca.common.model.cat.StoreCart;
import com.vca.common.model.category.Category;
import com.vca.common.model.course.Course;
import com.vca.common.model.course.CoursePackage;
import com.vca.common.model.course.CourseScheduling;
import com.vca.common.model.exhibition.Exhibition;
import com.vca.common.model.exhibition.ExhibitionScheduling;
import com.vca.common.model.lineUp.VcaLineUp;
import com.vca.common.model.order.StoreOrder;
import com.vca.common.model.order.StoreOrderInfo;
import com.vca.common.model.talk.Talk;
import com.vca.common.model.talk.TalkScheduling;
import com.vca.common.model.user.*;
import com.vca.common.model.vca_product.VcaProduct;
import com.vca.common.page.CommonPage;
import com.vca.common.request.*;
import com.vca.common.response.*;
import com.vca.common.token.FrontTokenComponent;
import com.vca.common.utils.*;
import com.vca.common.vo.GiftCardRelevanceVo;
import com.vca.common.vo.NoGetAppoinment;
import com.vca.common.vo.PreOrderCommonVo;
import com.vca.common.vo.dateLimitUtilVo;
import com.vca.service.dao.cart.StoreCartDao;
import com.vca.service.dao.category.CategoryDao;
import com.vca.service.dao.course.CourseDao;
import com.vca.service.dao.order.StoreOrderDao;
import com.vca.service.dao.order.StoreOrderInfoDao;
import com.vca.service.dao.talk.TalkDao;
import com.vca.service.dao.user.UserCardDao;
import com.vca.service.dao.user.UserCollectionDao;
import com.vca.service.dao.user.UserDao;
import com.vca.service.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;

/**
 * @author chenbing
 * @date 2022/10/8   15:11
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Resource
    private UserDao userDao;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserIntegralRecordService userIntegralRecordService;

    @Autowired
    private UserBillService userBillService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private SystemAttachmentService systemAttachmentService;

    @Autowired
    private FrontTokenComponent tokenComponet;

    @Resource
    private StoreOrderDao storeOrderDao;

    @Autowired
    private StoreOrderInfoService storeOrderInfoService;

    @Autowired
    private StoreOrderService storeOrderService;

    @Resource
    private StoreCartDao storeCartDao;

    @Resource
    private UserCardDao userCardDao;

    @Autowired
    private UserCardService userCardService;

    @Autowired
    private VcaUserCardRecordService vcaUserCardRecordService;

    @Resource
    private UserCollectionDao userCollectionDao;

    @Autowired
    private CourseService courseService;

    @Autowired
    private CategoryService categoryService;

    @Resource
    private CourseDao courseDao;

    @Resource
    private TalkDao talkDao;

    @Resource
    private CategoryDao categoryDao;

    @Autowired
    private UserAddressService userAddressService;

    @Resource
    private StoreOrderInfoDao storeOrderInfoDao;

    @Autowired
    private CoursePackageService coursePackageService;

    @Autowired
    private TalkService talkService;

    @Autowired
    private TalkSchedulingService talkSchedulingService;

    @Autowired
    private ExhibitionService exhibitionService;

    @Autowired
    private VcaProductService vcaProductService;

    @Autowired
    private VcaLineUpService vcaLineUpService;

    @Autowired
    private VcaOrderService vcaOrderService;

    @Autowired
    private CourseSchedulingService courseSchedulingService;

    @Autowired
    private ExhibitionSchedulingService exhibitionSchedulingService;

    @Autowired
    private SystemGroupDataService systemGroupDataService;

    /**
     * 用户信息
     *
     * @return
     */
    @Override
    public UserInfoResponse getUserCenter(String language) {
        User currentUser = getInfo();
        if (ObjectUtil.isNull(currentUser)) {
            throw new VcaException(ExceptionCodeEnum.UNAUTHORIZED.getMessage());
        }
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        BeanUtils.copyProperties(currentUser, userInfoResponse);

        List<String> address = Arrays.asList(StringUtils.split(currentUser.getAddres(), ","));
        userInfoResponse.setAddress(address);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(new Date());

        LambdaQueryWrapper<StoreOrderInfo> lqw = new LambdaQueryWrapper<>();
        lqw.between(StoreOrderInfo::getType, 0, 3);
        lqw.eq(StoreOrderInfo::getStatus, 1);
        lqw.eq(StoreOrderInfo::getRefundStatus, 0);
        //AND (( buyer = #{uid} AND ( buyer = lecturer OR is_get = 0 ) ) OR ( lecturer = #{uid} AND is_get = 1 ))
        lqw.last("AND (( buyer = " + currentUser.getUid() + " AND ( buyer = lecturer OR is_get = 0)) OR (lecturer = " + currentUser.getUid() + " AND is_get = 1))");
        //订单列表
        List<StoreOrderInfo> storeOrderInfoList = storeOrderInfoService.list(lqw);

        //根据type分组
        Map<Integer, List<StoreOrderInfo>> listMap = storeOrderInfoList.stream().collect(groupingBy(StoreOrderInfo::getType));

        // 课程数量
        userInfoResponse.setCoursesCount((listMap.get(0) == null ? 0 : listMap.get(0).size()) + (listMap.get(1) == null ? 0 : listMap.get(1).size()));
        // 讲座数量
        userInfoResponse.setTalkCount(listMap.get(2) == null ? 0 : listMap.get(2).size());
        // 展览数量
        userInfoResponse.setExhibitionsCount(listMap.get(3) == null ? 0 : listMap.get(3).size());

        //购物车查询
        LambdaQueryWrapper<StoreCart> cartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cartLambdaQueryWrapper.eq(StoreCart::getUid, currentUser.getUid());

        //购物车数量
        userInfoResponse.setShoppingCartsCount(storeCartDao.selectCount(cartLambdaQueryWrapper));

        //礼品卡查询
        LambdaQueryWrapper<UserCard> vcaUserCardLambdaQueryWrapper = new LambdaQueryWrapper<>();
        vcaUserCardLambdaQueryWrapper.eq(UserCard::getUid, currentUser.getUid());
        vcaUserCardLambdaQueryWrapper.eq(UserCard::getStutus, 0);
        vcaUserCardLambdaQueryWrapper.eq(UserCard::getIsDeleted, false);

        //礼品卡数量
        userInfoResponse.setGiftCardsCount(userCardDao.selectCount(vcaUserCardLambdaQueryWrapper));

        // 收藏数量查询
        LambdaQueryWrapper<UserCollection> userCollectionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userCollectionLambdaQueryWrapper.eq(UserCollection::getUid, currentUser.getUid());
        userCollectionLambdaQueryWrapper.eq(UserCollection::getType, "collect");
        userCollectionLambdaQueryWrapper.eq(UserCollection::getIsDeleted, false);
        //收藏数量
        userInfoResponse.setCollectionCount(userCollectionDao.selectCount(userCollectionLambdaQueryWrapper));

        //默收货地址
        UserAddressResponse aDefault = userAddressService.getDefault();
        userInfoResponse.setUserAddress(aDefault);

        // TODO: 2022/12/1 获取被赠送的课程/讲座/展览/套课订单信息
        List<NoGetAppoinment> noGetAppoinment = getNoGetAppoinment(language,currentUser);
        userInfoResponse.setNoGetAppoinment(noGetAppoinment);
        // TODO: 2022/12/21 获取排队集合
        List<LineUpResponse> lineUpResponses = getLineUpResponse(language,currentUser);
        userInfoResponse.setLineUpResponses(lineUpResponses);
        return userInfoResponse;
    }

    /**
     * @Description:获取排队集合
     * @author:chenbing
     * @date 2022/12/21 17:21
     */
    private List<LineUpResponse> getLineUpResponse(String language,User user) {
        List<VcaLineUp> lineUpList = vcaLineUpService.list(new LambdaQueryWrapper<VcaLineUp>()
                .eq(VcaLineUp::getUserId, user.getUid())
                .eq(VcaLineUp::getNoticeStatus, 1)
                .eq(VcaLineUp::getIsTip, 0));
        List<LineUpResponse> lineUpResponses = new ArrayList<>();
        for (VcaLineUp vcaLineUp : lineUpList) {
            LineUpResponse lineUpResponse = new LineUpResponse();
            BeanUtils.copyProperties(vcaLineUp, lineUpResponse);
            lineUpResponse.setMainType(vcaLineUp.getType());
            lineUpResponse.setNoticeStatus(vcaLineUp.getNoticeStatus());
            lineUpResponse.setLineUpId(vcaLineUp.getId());
            switch (vcaLineUp.getType()) {
                case 0:
                    if("en".equals(language)){
                        lineUpResponse.setTagText("Course");
                    }else{
                        lineUpResponse.setTagText("课程");
                    }
                    Course course = courseService.getById(vcaLineUp.getMainId());
                    lineUpResponse.setImagePath(course.getCover());

                    if("en".equals(language)){
                        lineUpResponse.setName(course.getNameEn());
                    }else{
                        lineUpResponse.setName(course.getName());
                    }

                    lineUpResponse.setThemeColor(categoryService.getById(course.getCourseTypeId()).getLabelColor());
                    break;
                case 1:
                    if("en".equals(language)){
                        lineUpResponse.setTagText("Overlapping lessons");
                    }else{
                        lineUpResponse.setTagText("套课");
                    }
                    CoursePackage coursePackage = coursePackageService.getById(vcaLineUp.getMainId());
                    lineUpResponse.setImagePath(coursePackage.getCoverImage());

                    if("en".equals(language)){
                        lineUpResponse.setName(coursePackage.getNameEn());
                    }else{
                        lineUpResponse.setName(coursePackage.getName());
                    }

                    lineUpResponse.setThemeColor(categoryService.getById(coursePackage.getCourseTypeId()).getLabelColor());
                    break;
                case 2:
                    if("en".equals(language)){
                        lineUpResponse.setTagText("Lecture");
                    }else{
                        lineUpResponse.setTagText("讲座");
                    }
                    Talk talk = talkService.getById(vcaLineUp.getMainId());
                    lineUpResponse.setImagePath(talk.getCoverImage());

                    if("en".equals(language)){
                        lineUpResponse.setName(talk.getNameEn());
                    }else{
                        lineUpResponse.setName(talk.getName());
                    }
                    lineUpResponse.setThemeColor("#B4B19E");

                    break;
                case 3:
                    if("en".equals(language)){
                        lineUpResponse.setTagText("Exhibition");
                    }else{
                        lineUpResponse.setTagText("展览");
                    }
                    Exhibition exhibition = exhibitionService.getById(vcaLineUp.getMainId());
                    lineUpResponse.setImagePath(exhibition.getCover());

                    if("en".equals(language)){
                        lineUpResponse.setName(exhibition.getNameEn());
                    }else{
                        lineUpResponse.setName(exhibition.getName());
                    }
                    lineUpResponse.setThemeColor("#B4B19E");
//                    lineUpResponse.setStartTime(DateUtil.dateToStr(exhibition.getStartTime(), Constants.DATE_FORMAT_DATE));
//                    lineUpResponse.setEndTime(DateUtil.dateToStr(exhibition.getEndTime(), Constants.DATE_FORMAT_DATE));
                    break;
                default:
                    break;
            }
            lineUpResponses.add(lineUpResponse);
        }
        return lineUpResponses;
    }

    /**
     * @Description:获取被赠送的课程/讲座/展览/套课订单信息
     * @author:chenbing
     * @date 2022/12/1 18:37
     */
    public List<NoGetAppoinment> getNoGetAppoinment(String language,User user) {
        LambdaQueryWrapper<StoreOrderInfo> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StoreOrderInfo::getIsGet, false);
        lqw.eq(StoreOrderInfo::getRefundStatus, 0);
        lqw.eq(StoreOrderInfo::getStatus, 1);
        lqw.ne(StoreOrderInfo::getType, 4);
        String sql = "";
        if (user.getUserRegisterType() == 1) {
            lqw.eq(StoreOrderInfo::getLecturerPhone, user.getPhone());
        }
        if (user.getUserRegisterType() == 2) {
            lqw.eq(StoreOrderInfo::getLecturerEmail, user.getEmail());
        }
        List<StoreOrderInfo> orderInfoList = storeOrderInfoService.list(lqw);
        List<NoGetAppoinment> noGetAppoinmentList = new ArrayList<>();
        if (orderInfoList.size() < 0) {
            return noGetAppoinmentList;
        }
        for (StoreOrderInfo orderInfo : orderInfoList) {
            NoGetAppoinment noGetAppoinment = new NoGetAppoinment();
            PreOrderCommonVo.CourseInfoDetail courseInfoDetail = JSONObject.parseObject(orderInfo.getInfo(), PreOrderCommonVo.CourseInfoDetail.class);
            List<PreOrderCommonVo.CourseInfoDetail.Scheduling> schedulings = courseInfoDetail.getSchedulings();
            List<NoGetAppoinment.AppointmentScheduling> appointmentSchedulings = new ArrayList<>();
            for (PreOrderCommonVo.CourseInfoDetail.Scheduling scheduling : schedulings) {
                NoGetAppoinment.AppointmentScheduling appointmentScheduling = new NoGetAppoinment.AppointmentScheduling();
                appointmentScheduling.setSchedulingDate(scheduling.getSchedulingDate());
                appointmentScheduling.setSchedulingEndTime(scheduling.getSchedulingEndTime());
                appointmentScheduling.setSchedulingStartTime(scheduling.getSchedulingStartTime());

                if("en".equals(language)){
                    appointmentScheduling.setName(scheduling.getCourseNameEn());
                }else{
                    appointmentScheduling.setName(scheduling.getCourseName());
                }
                appointmentSchedulings.add(appointmentScheduling);
            }
            noGetAppoinment.setType(orderInfo.getType());
            noGetAppoinment.setAppointmentSchedulings(appointmentSchedulings);

            if("en".equals(language)){
                noGetAppoinment.setName(orderInfo.getNameEn());
            }else{
                noGetAppoinment.setName(orderInfo.getName());
            }

            List<Integer> orderInfoIds = new ArrayList<>();
            orderInfoIds.add(orderInfo.getId());
            noGetAppoinment.setOrderInfoIds(orderInfoIds);
            noGetAppoinment.setOrderNo(orderInfo.getOrderNo());
//            List<List<Integer>> collect = noGetAppoinmentList.stream().map(NoGetAppoinment::getOrderInfoIds).collect(Collectors.toList());
//            List<Integer> orderInfoIdS = new ArrayList<>();
//            collect.forEach(c->{
//                c.forEach(orderInfoIdS::add);
//            });
            List<String> orderInfoIdS = noGetAppoinmentList.stream().map(NoGetAppoinment::getOrderNo).collect(Collectors.toList());
            noGetAppoinmentList.forEach(noGet -> {
                if (Objects.equals(noGet.getOrderNo(), orderInfo.getOrderNo())) {
                    if (!noGet.getOrderInfoIds().contains(orderInfo.getId())) {
                        noGet.getOrderInfoIds().add(orderInfo.getId());
                    }
                }
            });
            if (!orderInfoIdS.contains(orderInfo.getOrderNo())) {
                noGetAppoinmentList.add(noGetAppoinment);
            }
        }
        return noGetAppoinmentList;
    }

    /**
     * @Description: 修改用户信息
     * @Author: xyg
     * @Date: 2022/11/18
     */
    @Override
    public Boolean editUser(UserEditRequest request) {
        User user = getInfo();
        BeanUtils.copyProperties(request, user);
        String join = StringUtils.join(request.getAddress(), ",");
        user.setAddres(join);
        user.setUpdateTime(new Date());
        return updateById(user);
    }


    /**
     * @Description: 我的会员码
     * @Author: xyg
     * @Date: 2022/11/18
     */
    @Override
    public Map<String, String> getQrcode() {
        QrCodeResponse qrCodeResponse = new QrCodeResponse();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String code = "userid=" + getUserId().toString() + "&channel=wechat&time=" + System.currentTimeMillis();
        String qrCode = MiracleAECUtil.encrypt(code);
        HashMap<String, String> map = new HashMap<>();
        map.put("qrCode", qrCode);
        return map;
    }

    /**
     * 我预约的项目
     *
     * @param pageParamRequest
     * @param mainType         mainType 类型:0=课程 2=讲座 3=展览
     * @param
     * @return
     */
    @Override
    public PageInfo<MyAppointmentItemResponse> getAppointment(String language,PageParamRequest pageParamRequest, Integer mainType) {
        //分页
        Page<Object> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        List<MyAppointmentItemResponse> myAppointmentItemResponseList = new ArrayList();
        Integer userId = getUserId();

        List<StoreOrderInfo> storeOrderInfoList = new ArrayList<>();
        //如果类型是课程 则查询课程以及套课
        if (mainType.equals(0)) {
            ArrayList<Integer> types = new ArrayList<>();
            types.add(0);
            types.add(1);
            storeOrderInfoList = storeOrderInfoDao.getLecturerByUid(userId, types);
        } else {
            ArrayList<Integer> types = new ArrayList<>();
            types.add(mainType);
            storeOrderInfoList = storeOrderInfoDao.getLecturerByUid(userId, types);
        }
        for (StoreOrderInfo storeOrderInfo : storeOrderInfoList) {
            MyAppointmentItemResponse myAppointmentItemResponse = new MyAppointmentItemResponse();
            BeanUtils.copyProperties(storeOrderInfo, myAppointmentItemResponse);
            PreOrderCommonVo.CourseInfoDetail info = JSONObject.parseObject(storeOrderInfo.getInfo(), PreOrderCommonVo.CourseInfoDetail.class);
            //如果为套课 则id为课程id name为课程名称
            if (storeOrderInfo.getType().equals(1)) {
                System.out.println("33333333333");
                for (PreOrderCommonVo.CourseInfoDetail.Scheduling scheduling : info.getSchedulings()) {
                    if (scheduling.getCourseId().equals(storeOrderInfo.getTaokeAboutCourseId())) {
                        if("en".equals(language)){
                            myAppointmentItemResponse.setName(scheduling.getCourseNameEn());
                            myAppointmentItemResponse.setTypeName(getTypeNameEn(storeOrderInfo.getStatus()));
                        }else{
                            myAppointmentItemResponse.setName(scheduling.getCourseName());
                            myAppointmentItemResponse.setTypeName(getTypeName(storeOrderInfo.getStatus()));
                        }
                        myAppointmentItemResponse.setImagePath(scheduling.getCoverImage());
                        myAppointmentItemResponse.setId(storeOrderInfo.getTaokeAboutCourseId());
                        myAppointmentItemResponse.setMainType(0);
                    }
                }
            } else {
                System.out.println(info+"44444444");
                myAppointmentItemResponse.setImagePath(info.getCoverImage());
                myAppointmentItemResponse.setId(info.getMainId());

                if("en".equals(language)){
                    if(info.getNameEn() != null && !info.getNameEn().isEmpty()){
                        myAppointmentItemResponse.setName(info.getNameEn());
                    }
                    if(getTypeNameEn(storeOrderInfo.getStatus()) != null && !getTypeNameEn(storeOrderInfo.getStatus()).isEmpty()){
                        myAppointmentItemResponse.setTypeName(getTypeNameEn(storeOrderInfo.getStatus()));
                    }
                }else{
                    myAppointmentItemResponse.setName(info.getName());
                    myAppointmentItemResponse.setTypeName(getTypeName(storeOrderInfo.getStatus()));
                }
                myAppointmentItemResponse.setMainType(storeOrderInfo.getType());
            }

            if (storeOrderInfo.getStatus().equals(3)) {
                myAppointmentItemResponse.setStatus(2);
            }
            myAppointmentItemResponseList.add(myAppointmentItemResponse);
        }
        Map<Long, Category> appointmentList = new HashMap<>();
        System.out.println(myAppointmentItemResponseList+"========");
        if (!mainType.equals(3)) {
            // 课程 讲座 id
            List<Long> writeOffClerkIdList = myAppointmentItemResponseList.stream().map(MyAppointmentItemResponse::getId).distinct().collect(Collectors.toList());
            //课程的id和类别对象
            if (mainType.equals(0)) {
                appointmentList = getAppointmentList(writeOffClerkIdList);
            }
            //讲座对象
            HashMap<Long, Talk> talkHashMap = new HashMap<>();
            if (writeOffClerkIdList.size() > 0) {
                LambdaQueryWrapper<Talk> talkLambdaQueryWrapper = new LambdaQueryWrapper<>();
                talkLambdaQueryWrapper.in(Talk::getId, writeOffClerkIdList);
                talkLambdaQueryWrapper.eq(Talk::getIsDeleted, false);
                List<Talk> talks = talkDao.selectList(talkLambdaQueryWrapper);
                for (Talk talk : talks) {
                    talkHashMap.put(talk.getId(), talk);
                }
            }
            //给对象赋类别名称和颜色
            for (MyAppointmentItemResponse myAppointmentItemResponse : myAppointmentItemResponseList) {
                if (mainType.equals(0)) {
                    Category category = appointmentList.get(myAppointmentItemResponse.getId());
                    if (ObjectUtil.isNotEmpty(category)) {
                        myAppointmentItemResponse.setThemeColor(appointmentList.get(myAppointmentItemResponse.getId()).getLabelColor());
                        if("en".equals(language)){
                            myAppointmentItemResponse.setTagText(appointmentList.get(myAppointmentItemResponse.getId()).getNameEn());
                        }else{
                            myAppointmentItemResponse.setTagText(appointmentList.get(myAppointmentItemResponse.getId()).getName());
                        }
                    }
                } else if (mainType.equals(2)) {
                    myAppointmentItemResponse.setThemeColor("#B4B19E");
                    Talk talk = talkHashMap.get(myAppointmentItemResponse.getId());
                    if (ObjectUtil.isNotEmpty(talk)) {
                        if("en".equals(language)){
                            myAppointmentItemResponse.setTagText(talkHashMap.get(myAppointmentItemResponse.getId()).getTalkType() == 1 ? "In-person Talk" : "Online Talk");
                        }else{
                            myAppointmentItemResponse.setTagText(talkHashMap.get(myAppointmentItemResponse.getId()).getTalkType() == 1 ? "线下讲座" : "线上讲座");
                        }

                    }
                }
            }
        }
        return CommonPage.copyPageInfo(page, myAppointmentItemResponseList);
    }

    /**
     * @Description: 我的礼品卡
     * @Author: xyg
     * @Date: 2022/11/21
     */
    @Override
    public PageInfo<GiftCardResponse> getCard(String language,String preOrderNo, PageParamRequest pageParamRequest) {
        Integer userId = getUserId();
        LambdaQueryWrapper<UserCard> userCardLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userCardLambdaQueryWrapper.eq(UserCard::getUid, userId);
        userCardLambdaQueryWrapper.eq(UserCard::getStutus, 0);
        userCardLambdaQueryWrapper.eq(UserCard::getIsDeleted, false);
        PreOrderCommonResponse loadPreCommon = new PreOrderCommonResponse();
        Integer cid = 0;
        PreOrderCommonVo preOrderCommonVo = new PreOrderCommonVo();
        if (StringUtils.isNotBlank(preOrderNo)) {
            loadPreCommon = vcaOrderService.loadPreCommon(language,preOrderNo);
            preOrderCommonVo = loadPreCommon.getPreOrderCommonVo();
            Integer type = preOrderCommonVo.getType();
            PreOrderCommonVo.CourseInfoDetail.Scheduling scheduling = preOrderCommonVo.getEventInfoDetail().getSchedulings().get(0);
            Long courseId = scheduling.getCourseId();
            Long scheduleId = scheduling.getScheduleId();
            // TODO: 2022/12/21 查询当前课程属性详情
            switch (type) {
                case 0:
                    userCardLambdaQueryWrapper.eq(UserCard::getUserAround, 0);
                    Course course = courseService.getById(courseId);
                    BigDecimal price1 = courseService.getPrice(courseSchedulingService.getById(scheduleId).getPriceId());
                    userCardLambdaQueryWrapper.eq(UserCard::getFaceValue, price1);
                    cid = Math.toIntExact(course.getCourseTypeId());
                    break;
                case 2:
                    userCardLambdaQueryWrapper.eq(UserCard::getUserAround, 1);
                    Talk talk = talkService.getById(courseId);
                    TalkScheduling talkScheduling = talkSchedulingService.getById(scheduleId);
                    userCardLambdaQueryWrapper.eq(UserCard::getFaceValue, talkScheduling.getPrice());
                    cid = Math.toIntExact(talk.getTalkType());
                    break;
                case 3:
                    userCardLambdaQueryWrapper.eq(UserCard::getUserAround, 2);
                    userCardLambdaQueryWrapper.eq(UserCard::getFaceValue, exhibitionSchedulingService.getById(scheduleId).getPrice());
                    break;
                default:
                    break;
            }

        }

        userCardLambdaQueryWrapper.orderByAsc(UserCard::getEndTime);
        List<UserCard> userCards = userCardDao.selectList(userCardLambdaQueryWrapper);
        System.out.println(userCards+"--------------");
        List<UserCard> retainGiftCards = new ArrayList<>();
        if (StringUtils.isNotBlank(preOrderNo)) {
            Integer type = preOrderCommonVo.getType();
            PreOrderCommonVo.CourseInfoDetail.Scheduling scheduling = preOrderCommonVo.getEventInfoDetail().getSchedulings().get(0);
            Long courseId = scheduling.getCourseId();
            Long scheduleId = scheduling.getScheduleId();
            for (UserCard userCard : userCards) {
                List<String> strings = new ArrayList<>();
                if (ObjectUtil.isNotNull(userCard.getPrimaryKey())) {
                    strings = Arrays.asList(userCard.getPrimaryKey().split(","));
                }
                if (userCard.getUseType() == 3) {
                    retainGiftCards.add(userCard);
                    continue;
                }
                if (type == 0) {
                    if (containsCid(cid, strings) || containsMainId(courseId, strings)) {
                        retainGiftCards.add(userCard);
                    }
                }
                if (type == 2) {
                    if (containsCid(cid, strings) || containsMainId(courseId, strings)) {
                        retainGiftCards.add(userCard);
                    }
                }
                if (type == 3) {
                    if (containsMainId(courseId, strings)) {
                        retainGiftCards.add(userCard);
                    }
                }
            }
            userCards.retainAll(retainGiftCards);
        }
        System.out.println(userCards+"===============");
        List<GiftCardResponse> giftCardResponseList = new ArrayList<>();
        for (UserCard userCard : userCards) {
            GiftCardResponse giftCardResponse = new GiftCardResponse();
            BeanUtils.copyProperties(userCard, giftCardResponse);
            if("en".equals(language)){
                giftCardResponse.setName(giftCardResponse.getNameEn());
            }
            giftCardResponse.setFaceValue(userCard.getFaceValue());
            giftCardResponse.setStartTime(DateUtil.dateToStr(userCard.getStartTime(), Constants.DATE_FORMAT_DATE));
            giftCardResponse.setEndTime(DateUtil.dateToStr(userCard.getEndTime(), Constants.DATE_FORMAT_DATE));
            giftCardResponse.setUsedTime(DateUtil.dateToStr(userCard.getUseTime(), Constants.DATE_FORMAT_DATE));
            giftCardResponseList.add(giftCardResponse);
        }
        if (StringUtils.isNotBlank(preOrderNo)) {
            return PageUtils.startPage(giftCardResponseList, pageParamRequest.getPage(), pageParamRequest.getLimit());
        } else {
            Page<Object> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
            return CommonPage.copyPageInfo(page, giftCardResponseList);
        }
    }

    private boolean containsMainId(Long courseId, List<String> strings) {
        for (String s : strings) {
            Long s1 = Long.valueOf(s);
            if (s1.equals(courseId)) {
                return true;
            }
        }
        return false;
    }

    private boolean containsCid(Integer cid, List<String> strings) {
        for (String s : strings) {
            Integer s1 = Integer.valueOf(s);
            if (s1.equals(cid)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @Description:礼品卡领取页详情
     * @author:chenbing
     * @date 2023/6/27 9:27
     */
    @Override
    public HashMap<String, Object> cardInfoClaim(String cardNo) {
        HashMap<String, Object> map = new HashMap<>();
        UserCard userCard = userCardService.getOne(new LambdaQueryWrapper<UserCard>().eq(UserCard::getCardNo, cardNo));
        if (userCard == null) {
            throw new VcaException("当前礼品卡不存在");
        }
        Integer userId = getUserId();
        map.put("userId", userId);
        map.put("cardId", userCard.getId());
        map.put("cardNo", cardNo);
        map.put("owner", userCard.getUid());
        StoreOrderInfo orderInfo = storeOrderInfoService.getOne(new LambdaQueryWrapper<StoreOrderInfo>().eq(StoreOrderInfo::getMerOrderNo, userCard.getOrderId()));
        if (orderInfo != null) {
            StoreOrder storeOrder = vcaOrderService.getOne(new LambdaQueryWrapper<StoreOrder>().eq(StoreOrder::getOrderId, orderInfo.getOrderNo()));
            map.put("buyer", storeOrder != null ? storeOrder.getUid() : userCard.getUid());
        }
        return map;
    }

    /**
     * 礼品卡详情
     *
     * @param id
     * @return
     */
    @Override
    public GiftCardInfoResponse getCardInfo(String language,Integer id) {

        GiftCardInfoResponse giftCardInfoResponse = new GiftCardInfoResponse();

        ArrayList<GiftCardRelevanceVo> giftCardRelevanceVos = new ArrayList<>();
        //礼品卡信息
        UserCard userCard = userCardService.getOne(new LambdaQueryWrapper<UserCard>().eq(UserCard::getId, id));
        if (ObjectUtil.isNull(userCard)) {
            if("en".equals(language)){
                throw new VcaException("The gift card does not exist!");
            }else{
                throw new VcaException("该礼品卡不存在！");
            }
        }

        BeanUtils.copyProperties(userCard, giftCardInfoResponse);
        giftCardInfoResponse.setUseAround(userCard.getUserAround());
        giftCardInfoResponse.setFaceValue(userCard.getFaceValue());
        giftCardInfoResponse.setStartTime(DateUtil.dateToStr(userCard.getStartTime(), Constants.DATE_FORMAT_DATE));
        giftCardInfoResponse.setEndTime(DateUtil.dateToStr(userCard.getEndTime(), Constants.DATE_FORMAT_DATE));
        giftCardInfoResponse.setUsedTime(DateUtil.dateToStr(userCard.getUseTime(), Constants.DATE_FORMAT_DATE));
        System.out.println(userCard+"-------------");
        if(ObjectUtil.isEmpty(userCard.getCardType())||userCard.getUseType().equals(1)){
            LambdaQueryWrapper<StoreOrderInfo> storeOrderInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            storeOrderInfoLambdaQueryWrapper.eq(StoreOrderInfo::getMerOrderNo, userCard.getOrderId());
            StoreOrderInfo storeOrderInfo = storeOrderInfoService.getOne(storeOrderInfoLambdaQueryWrapper);
            System.out.println(storeOrderInfo+"=============");
            StoreOrder storeOrder = storeOrderService.getByOrderId(storeOrderInfo.getOrderNo());

            giftCardInfoResponse.setIsGive(storeOrder.getUid().equals(userCard.getUid()) ? 1 : 0);
        }else {
            giftCardInfoResponse.setIsGive(0);
        }
               //如果所属课程id / 分类id 为空 则返回null
        if (StringUtils.isBlank(userCard.getPrimaryKey()) && !userCard.getUseType().equals(3)) {
            return giftCardInfoResponse;
        }
        // 0=课程 1=讲座 2=展览
        switch (userCard.getUserAround()) {
            case 0:
                if (userCard.getUseType().equals(1)) { //如果是分类卡 则查询该分类下对应的课程/讲座  展览没有分类卡
                    //分类id集合
                    List<Integer> ids = Arrays.stream(userCard.getPrimaryKey().split(",")).map(Integer::parseInt).collect(Collectors.toList());
                    //类别集合
                    List<Category> categoryList = categoryService.list(new LambdaQueryWrapper<Category>().in(Category::getId, ids).eq(Category::getIsDel, false));
                    if (CollUtil.isEmpty(categoryList)) {
                        if("en".equals(language)){
                            throw new VcaException("The course classification card does not have a corresponding classification!");
                        }else{
                            throw new VcaException("该课程分类卡没有对应的分类！");
                        }
                    }
                    //类别id集合
                    ArrayList<Integer> cids = new ArrayList<>();
                    for (Category category : categoryList) {
                        cids.add(category.getId());
                    }
                    //课程集合
                    List<Course> courseList = courseService.list(new LambdaQueryWrapper<Course>().in(Course::getCourseTypeId, cids).eq(Course::getIsDeleted, false));
                    if (CollUtil.isEmpty(courseList)) {
                        return giftCardInfoResponse;
                    }
                    for (Course course : courseList) {
                        //对应排期
                        List<CourseScheduling> courseSchedulings = courseSchedulingService.list(new LambdaQueryWrapper<CourseScheduling>().eq(CourseScheduling::getCourseId, course.getId()).eq(CourseScheduling::getIsDel, false).eq(CourseScheduling::getIsCancel, 0));
                        if (CollUtil.isEmpty(courseSchedulings)) {
                            return giftCardInfoResponse;
                        }
                        //排期价格id集合
                        List<Integer> priceIds = courseSchedulings.stream().map(CourseScheduling::getPriceId).distinct().collect(Collectors.toList());
                        Boolean isEquals = false;
                        for (Integer priceId : priceIds) {
                            //判断排期价格是否跟礼品卡面值相等
                            BigDecimal price = getPriceIdByPrice(priceId);
                            if (ObjectUtil.isNull(price)) {
                                if("en".equals(language)){
                                    throw new VcaException("The price ID does not exist:"+priceId);
                                }else{
                                    throw new VcaException("该价格id不存在： " + priceId);
                                }
                            }
                            if (price.compareTo(userCard.getFaceValue()) == 0) {
                                isEquals = true;
                            }
                        }
                        if (isEquals) {
                            GiftCardRelevanceVo giftCardRelevanceVo = new GiftCardRelevanceVo();
                            giftCardRelevanceVo.setId(course.getId());
                            if("en".equals(language)){
                                giftCardRelevanceVo.setName(course.getNameEn());
                            }else{
                                giftCardRelevanceVo.setName(course.getName());
                            }
                            giftCardRelevanceVos.add(giftCardRelevanceVo);
                        }

                    }
                } else if (userCard.getUseType().equals(2)) { //课程卡
                    //课程id集合
                    List<Integer> ids = Arrays.stream(userCard.getPrimaryKey().split(",")).map(Integer::parseInt).collect(Collectors.toList());
                    //课程集合
                    List<Course> courseList = courseService.list(new LambdaQueryWrapper<Course>().in(Course::getId, ids).eq(Course::getIsDeleted, false));
                    if (CollUtil.isEmpty(courseList)) {
                        return giftCardInfoResponse;
                    }
                    for (Course course : courseList) {
                        //对应排期
                        List<CourseScheduling> courseSchedulings = courseSchedulingService.list(new LambdaQueryWrapper<CourseScheduling>().eq(CourseScheduling::getCourseId, course.getId()).eq(CourseScheduling::getIsDel, false).eq(CourseScheduling::getIsCancel, 0));
                        if (CollUtil.isEmpty(courseSchedulings)) {
                            return giftCardInfoResponse;
                        }
                        //排期价格id集合
                        List<Integer> priceIds = courseSchedulings.stream().map(CourseScheduling::getPriceId).distinct().collect(Collectors.toList());
                        Boolean isEquals = false;
                        for (Integer priceId : priceIds) {
                            //判断排期价格是否跟礼品卡面值相等
                            BigDecimal price = getPriceIdByPrice(priceId);
                            if (ObjectUtil.isNull(price)) {
                                if("en".equals(language)){
                                    throw new VcaException("The price ID does not exist:"+priceId);
                                }else{
                                    throw new VcaException("该价格id不存在： " + priceId);
                                }
                            }
                            if (price.compareTo(userCard.getFaceValue()) == 0) {
                                isEquals = true;
                            }
                        }
                        if (isEquals) {
                            GiftCardRelevanceVo giftCardRelevanceVo = new GiftCardRelevanceVo();
                            giftCardRelevanceVo.setId(course.getId());
                            if("en".equals(language)){
                                giftCardRelevanceVo.setName(course.getNameEn());
                            }else{
                                giftCardRelevanceVo.setName(course.getName());
                            }
                            giftCardRelevanceVos.add(giftCardRelevanceVo);
                        }
                    }
                } else if (userCard.getUseType().equals(3)) { //通用卡

                    List<Integer> priceIds = getPriceIdByFaceValue(userCard.getFaceValue());

                    //对应面值的排期集合
                    List<CourseScheduling> courseSchedulings = courseSchedulingService.list(new LambdaQueryWrapper<CourseScheduling>().in(CourseScheduling::getPriceId, priceIds).eq(CourseScheduling::getIsDel, false).eq(CourseScheduling::getIsCancel, 0));

                    if (CollUtil.isEmpty(courseSchedulings)) {
                        return giftCardInfoResponse;
                    }
                    //课程id集合
                    List<Long> courseIds = courseSchedulings.stream().map(CourseScheduling::getCourseId).distinct().collect(Collectors.toList());
                    //课程集合
                    List<Course> courseList = courseService.list(new LambdaQueryWrapper<Course>().in(Course::getId, courseIds).eq(Course::getIsDeleted, false));

                    if (CollUtil.isEmpty(courseList)) {
                        return giftCardInfoResponse;
                    }
                    for (Course course : courseList) {
                        GiftCardRelevanceVo giftCardRelevanceVo = new GiftCardRelevanceVo();
                        giftCardRelevanceVo.setId(course.getId());
                        if("en".equals(language)){
                            giftCardRelevanceVo.setName(course.getName());
                        }else{
                            giftCardRelevanceVo.setName(course.getNameEn());
                        }

                        giftCardRelevanceVos.add(giftCardRelevanceVo);
                    }
                }
                giftCardInfoResponse.setGiftCardRelevanceVoList(giftCardRelevanceVos);
                break;
            case 1:
                if (userCard.getUseType().equals(1)) { //如果是分类卡 则查询该分类下对应的讲座

                    //讲座集合
                    List<Talk> talkList = talkService.list(new LambdaQueryWrapper<Talk>().eq(Talk::getTalkType, Integer.valueOf(userCard.getPrimaryKey())).eq(Talk::getIsDeleted, false));

                    if (CollUtil.isEmpty(talkList)) {
                        return giftCardInfoResponse;
                    }
                    for (Talk talk : talkList) {
                        List<TalkScheduling> talkSchedulings = talkSchedulingService.list(new LambdaQueryWrapper<TalkScheduling>().eq(TalkScheduling::getTalkId, talk.getId()).eq(TalkScheduling::getIsCancel, 0).eq(TalkScheduling::getIsDeleted, false));
                        if (CollUtil.isEmpty(talkSchedulings)) {
                            return giftCardInfoResponse;
                        }
                        //对应排期去重后的价格集合
                        List<BigDecimal> prices = talkSchedulings.stream().map(TalkScheduling::getPrice).collect(Collectors.toList());
                        Boolean isEquals = false;
                        for (BigDecimal price : prices) {
                            if (price.compareTo(userCard.getFaceValue()) == 0) {
                                isEquals = true;
                            }
                        }
                        if (isEquals) {
                            GiftCardRelevanceVo giftCardRelevanceVo = new GiftCardRelevanceVo();
                            giftCardRelevanceVo.setId(talk.getId());
                            if("en".equals(language)){
                                giftCardRelevanceVo.setName(talk.getName());
                            }else{
                                giftCardRelevanceVo.setName(talk.getNameEn());
                            }
                            giftCardRelevanceVos.add(giftCardRelevanceVo);
                        }
                    }
                } else if (userCard.getUseType().equals(2)) { //讲座卡
                    //讲座id集合
                    List<Integer> ids = Arrays.stream(userCard.getPrimaryKey().split(",")).map(Integer::parseInt).collect(Collectors.toList());
                    //讲座集合
                    List<Talk> talkList = talkService.list(new LambdaQueryWrapper<Talk>().in(Talk::getId, ids).eq(Talk::getIsDeleted, false));
                    if (CollUtil.isEmpty(talkList)) {
                        return giftCardInfoResponse;
                    }
                    for (Talk talk : talkList) {

                        List<TalkScheduling> talkSchedulings = talkSchedulingService.list(new LambdaQueryWrapper<TalkScheduling>().eq(TalkScheduling::getTalkId, talk.getId()).eq(TalkScheduling::getIsCancel, 0).eq(TalkScheduling::getIsDeleted, false));
                        if (CollUtil.isEmpty(talkSchedulings)) {
                            return giftCardInfoResponse;
                        }
                        //对应排期去重后的价格集合
                        List<BigDecimal> prices = talkSchedulings.stream().map(TalkScheduling::getPrice).collect(Collectors.toList());
                        Boolean isEquals = false;
                        for (BigDecimal price : prices) {
                            if (price.compareTo(userCard.getFaceValue()) == 0) {
                                isEquals = true;
                            }
                        }
                        if (isEquals) {
                            GiftCardRelevanceVo giftCardRelevanceVo = new GiftCardRelevanceVo();
                            giftCardRelevanceVo.setId(talk.getId());
                            if("en".equals(language)){
                                giftCardRelevanceVo.setName(talk.getName());
                            }else{
                                giftCardRelevanceVo.setName(talk.getNameEn());
                            }
                            giftCardRelevanceVos.add(giftCardRelevanceVo);
                        }
                    }
                } else if (userCard.getUseType().equals(3)) { //通用卡
                    List<TalkScheduling> talkSchedulings = talkSchedulingService.list(new LambdaQueryWrapper<TalkScheduling>().eq(TalkScheduling::getPrice, userCard.getFaceValue()).eq(TalkScheduling::getIsCancel, 0).eq(TalkScheduling::getIsDeleted, false));
                    if (CollUtil.isEmpty(talkSchedulings)) {
                        return giftCardInfoResponse;
                    }
                    //讲座id集合
                    List<Long> talkIds = talkSchedulings.stream().map(TalkScheduling::getTalkId).distinct().collect(Collectors.toList());
                    //讲座集合
                    List<Talk> talkList = talkService.list(new LambdaQueryWrapper<Talk>().in(Talk::getId, talkIds).eq(Talk::getIsDeleted, false));

                    if (CollUtil.isEmpty(talkList)) {
                        return giftCardInfoResponse;
                    }
                    for (Talk talk : talkList) {
                        GiftCardRelevanceVo giftCardRelevanceVo = new GiftCardRelevanceVo();
                        giftCardRelevanceVo.setId(talk.getId());
                        if("en".equals(language)){
                            giftCardRelevanceVo.setName(talk.getName());
                        }else{
                            giftCardRelevanceVo.setName(talk.getNameEn());
                        }
                        giftCardRelevanceVos.add(giftCardRelevanceVo);
                    }
                }
                giftCardInfoResponse.setGiftCardRelevanceVoList(giftCardRelevanceVos);
                break;
            case 2:
                if (userCard.getUseType().equals(2)) { //展览卡
                    //展览id集合
                    List<Integer> ids = Arrays.stream(userCard.getPrimaryKey().split(",")).map(Integer::parseInt).collect(Collectors.toList());
                    //展览集合
                    List<Exhibition> exhibitionList = exhibitionService.list(new LambdaQueryWrapper<Exhibition>().in(Exhibition::getId, ids).eq(Exhibition::getIsDeleted, false));
                    if (CollUtil.isEmpty(exhibitionList)) {
                        return giftCardInfoResponse;
                    }
                    for (Exhibition exhibition : exhibitionList) {
                        List<ExhibitionScheduling> exhibitionSchedulings = exhibitionSchedulingService.list(new LambdaQueryWrapper<ExhibitionScheduling>().eq(ExhibitionScheduling::getExhibitionId, exhibition.getId()).eq(ExhibitionScheduling::getIsCancel, 0).eq(ExhibitionScheduling::getIsDeleted, false));
                        if (CollUtil.isEmpty(exhibitionSchedulings)) {
                            return giftCardInfoResponse;
                        }
                        //去重后的排期价格集合
                        List<BigDecimal> prices = exhibitionSchedulings.stream().map(ExhibitionScheduling::getPrice).collect(Collectors.toList());
                        Boolean isEquals = false;
                        for (BigDecimal price : prices) {
                            if (price.compareTo(userCard.getFaceValue()) == 0) {
                                isEquals = true;
                            }
                        }
                        if (isEquals) {
                            GiftCardRelevanceVo giftCardRelevanceVo = new GiftCardRelevanceVo();
                            giftCardRelevanceVo.setId(exhibition.getId());
                            if("en".equals(language)){
                                giftCardRelevanceVo.setName(exhibition.getName());
                            }else{
                                giftCardRelevanceVo.setName(exhibition.getNameEn());
                            }
                            giftCardRelevanceVos.add(giftCardRelevanceVo);
                        }
                    }
                } else if (userCard.getUseType().equals(3)) { //通用卡
                    //展览排期集合
                    List<ExhibitionScheduling> exhibitionSchedulings = exhibitionSchedulingService.list(new LambdaQueryWrapper<ExhibitionScheduling>().eq(ExhibitionScheduling::getPrice, userCard.getFaceValue()).eq(ExhibitionScheduling::getIsDeleted, false).eq(ExhibitionScheduling::getIsCancel, 0));
                    if (CollUtil.isEmpty(exhibitionSchedulings)) {
                        return giftCardInfoResponse;
                    }
                    //展览id集合
                    List<Long> exhibitionIds = exhibitionSchedulings.stream().map(ExhibitionScheduling::getExhibitionId).distinct().collect(Collectors.toList());
                    List<Exhibition> exhibitionList = exhibitionService.list(new LambdaQueryWrapper<Exhibition>().in(Exhibition::getId, exhibitionIds).eq(Exhibition::getIsDeleted, false));
                    for (Exhibition exhibition : exhibitionList) {
                        GiftCardRelevanceVo giftCardRelevanceVo = new GiftCardRelevanceVo();
                        giftCardRelevanceVo.setId(exhibition.getId());
                        if("en".equals(language)){
                            giftCardRelevanceVo.setName(exhibition.getName());
                        }else{
                            giftCardRelevanceVo.setName(exhibition.getNameEn());
                        }
                        giftCardRelevanceVos.add(giftCardRelevanceVo);
                    }
                }
                giftCardInfoResponse.setGiftCardRelevanceVoList(giftCardRelevanceVos);
                break;
            default:
                break;
        }
        return giftCardInfoResponse;
    }

    /**
     * 根据课程价格id获取课程价格
     *
     * @param priceId
     * @return
     */
    public BigDecimal getPriceIdByPrice(Integer priceId) {

        BigDecimal price = null;
        List<HashMap<String, Object>> listMapByGid = systemGroupDataService.getListMapByGidAll("",SysGroupDataConstants.GROUP_DATA_ID_CLIENT_COURSE_PRICE, false);
        for (HashMap<String, Object> stringObjectHashMap : listMapByGid) {
            Integer id = Integer.valueOf(String.valueOf(stringObjectHashMap.get("id")));
            if (id.equals(priceId)) {
                String coursePrice = String.valueOf(stringObjectHashMap.get("coursePrice"));
                price = new BigDecimal(coursePrice);
            }
        }
//        listMapByGid.forEach(e->{
//            Integer id = Integer.valueOf(String.valueOf(e.get("id")));
//            if (id.equals(priceId)){
//                String coursePrice = String.valueOf(e.get("coursePrice"));
//                BigDecimal price = new BigDecimal(coursePrice);
//                return price;
//            }
        return price;
    }

    /**
     * 根据礼品卡面值获取课程价格id
     *
     * @param faceValue
     * @return
     */
    public List<Integer> getPriceIdByFaceValue(BigDecimal faceValue) {

        ArrayList<Integer> priceId = new ArrayList<>();
        List<HashMap<String, Object>> listMapByGid = systemGroupDataService.getListMapByGid(SysGroupDataConstants.GROUP_DATA_ID_CLIENT_COURSE_PRICE);
        listMapByGid.forEach(e -> {
            String coursePrice = String.valueOf(e.get("coursePrice"));
            BigDecimal price = new BigDecimal(coursePrice);
            if (price.compareTo(faceValue) == 0) {
                priceId.add(Integer.valueOf(e.get("id").toString()));
            }
        });
        return priceId;
    }

    /**
     * @Description:获取相应的礼品卡
     * @author:chenbing
     * @date 2022/12/21 14:50
     */
    @Override
    public PageInfo<GiftCardResponse> getCardList(Long mainId, Integer type, PageParamRequest pageParamRequest) {
        Integer userId = getUserId();
        LambdaQueryWrapper<UserCard> userCardLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userCardLambdaQueryWrapper.eq(UserCard::getUid, userId);
        userCardLambdaQueryWrapper.eq(UserCard::getStutus, 0);
        userCardLambdaQueryWrapper.eq(UserCard::getIsDeleted, false);
        // TODO: 2022/12/21 查询当前课程属性详情
        Integer cid = 0;
        switch (type) {
            case 0:
                userCardLambdaQueryWrapper.eq(UserCard::getUserAround, 0);
                Course course = courseService.getById(mainId);
                cid = Math.toIntExact(course.getCourseTypeId());
                break;
            case 2:
                userCardLambdaQueryWrapper.eq(UserCard::getUserAround, 1);
                Talk talk = talkService.getById(mainId);
                cid = Math.toIntExact(talk.getTalkType());
                break;
            case 3:
                userCardLambdaQueryWrapper.eq(UserCard::getUserAround, 2);
                break;
            default:
                break;
        }
        userCardLambdaQueryWrapper.orderByAsc(UserCard::getEndTime);
        List<UserCard> userCards = userCardDao.selectList(userCardLambdaQueryWrapper);
        List<UserCard> userCardList = new ArrayList<>();
        for (UserCard userCard : userCards) {
            switch (userCard.getUseType()) {
                case 1:
                    //分类卡
                    List<String> cids = Arrays.asList(userCard.getPrimaryKey().split(","));
                    if (cids.contains(cid)) {
                        userCardList.add(userCard);
                    }
                    break;
                case 2:
                    //课程卡
                    List<String> mainIds = Arrays.asList(userCard.getPrimaryKey().split(","));
                    if (mainIds.contains(mainId)) {
                        userCardList.add(userCard);
                    }
                    break;
                case 3:
                    //通用卡
                    userCardList.add(userCard);
                    break;
                default:
                    break;
            }

        }
        List<GiftCardResponse> giftCardResponseList = new ArrayList<>();
        userCardList.forEach(e -> {
            GiftCardResponse giftCardResponse = new GiftCardResponse();
            BeanUtils.copyProperties(e, giftCardResponse);
            giftCardResponse.setStartTime(DateUtil.dateToStr(e.getStartTime(), Constants.DATE_FORMAT_DATE));
            giftCardResponse.setEndTime(DateUtil.dateToStr(e.getEndTime(), Constants.DATE_FORMAT_DATE));
            giftCardResponse.setUsedTime(DateUtil.dateToStr(e.getUseTime(), Constants.DATE_FORMAT_DATE));
            giftCardResponseList.add(giftCardResponse);
        });
        Page<Object> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        return CommonPage.copyPageInfo(page, giftCardResponseList);
    }

    /**
     * @param cardKey 礼品卡序列号
     * @Description:兑换礼品卡
     * @author:chenbing
     * @date 2023/9/26 10:24
     */
    @Override
    public boolean exchangeCard(String language,String cardKey) {
        Integer userId = getUserIdException();
        UserCard userCard = userCardService.getOne(new LambdaQueryWrapper<UserCard>().eq(UserCard::getCdKey, cardKey).eq(UserCard::getIsDeleted, false));
        if (userCard == null) {
            if("en".equals(language)){
                throw new VcaException("Gift certificate serial number is incorrect or expired");
            }else{
                throw new VcaException("礼品卡序列号错误或已失效");
            }
        }
        if (userCard.getUid() != 0) {
            if("en".equals(language)){
                throw new VcaException("Gift certificate serial number is incorrect or expired");
            }else{
                throw new VcaException("礼品卡序列号错误或已失效");
            }
        }
        userCard.setUid(userId);
        userCard.setGiftTime(new Date());
        Boolean execute = transactionTemplate.execute(e -> {
            userCardService.updateById(userCard);
            VcaUserCardRecord vcaUserCardRecord = vcaUserCardRecordService.getOne(new LambdaQueryWrapper<VcaUserCardRecord>().eq(VcaUserCardRecord::getCardId, userCard.getId()));
            if (vcaUserCardRecord == null) {
                vcaUserCardRecord = new VcaUserCardRecord();
            }
            vcaUserCardRecord.setCardId(userCard.getId());
            vcaUserCardRecord.setGetUser(userId);
            vcaUserCardRecord.setSendUser(0);
            vcaUserCardRecord.setCreateTime(new Date());
            if("en".equals(language)){
                vcaUserCardRecord.setDescription(getById(userId).getNickname() + " redeems a gift certificate with the serial number " + cardKey + "");
            }else{
                vcaUserCardRecord.setDescription(getById(userId).getNickname() + "兑换了序列号为【" + cardKey + "】的礼品卡");
            }

            vcaUserCardRecordService.save(vcaUserCardRecord);
            return Boolean.TRUE;
        });
        if (!execute) {
            if("en".equals(language)){
                throw new VcaException("Gift certificate serial number is incorrect or expired");
            }else{
                throw new VcaException("礼品卡序列号错误或已失效");
            }
        }
        return true;
    }

    /**
     * 我的收藏
     *
     * @param pageParamRequest
     * @return
     */
    @Override
    public PageInfo<CollectionsResponse> getCollections(String language,PageParamRequest pageParamRequest) {
        Page<Object> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        Integer userId = getUserId();
        LambdaQueryWrapper<UserCollection> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserCollection::getUid, userId);
        lambdaQueryWrapper.eq(UserCollection::getType, "collect");
        lambdaQueryWrapper.eq(UserCollection::getIsDeleted, false);
        lambdaQueryWrapper.orderByDesc(UserCollection::getCreateTime);
        List<UserCollection> userCollections = userCollectionDao.selectList(lambdaQueryWrapper);

        //课程map
        HashMap<Long, Course> courseMap = new HashMap<>();
        //课程类别map
        HashMap<Long, Category> courseCatMap = new HashMap<>();
        //套程map
        HashMap<Long, CoursePackage> packageCourseMap = new HashMap<>();
        //套程类别map
        HashMap<Long, Category> packageCourseCatMap = new HashMap<>();
        //讲座排期map
//        HashMap<Long, TalkScheduling> talkSchedulingMap = new HashMap<>();
        Map<Long, List<TalkScheduling>> talkSchedulingMap = new HashMap<>();
        //讲座map
        HashMap<Long, Talk> talkMap = new HashMap<>();
        //展览map
        HashMap<Long, Exhibition> exhibitionMap = new HashMap<>();
        //商品map
        HashMap<Integer, VcaProduct> productMap = new HashMap<>();
        //商品类别map
        HashMap<Integer, Category> productCatMap = new HashMap<>();

//        //课程价格map
//        HashMap<Long, SystemGroupData> coursePriceMap = new HashMap<>();
        //根据类型分组
        Map<Integer, List<UserCollection>> collect = userCollections.stream().collect(groupingBy(UserCollection::getMainType));
        //课程
        if (ObjectUtil.isNotNull(collect.get(0))) {
            //课程id集合
            List<Long> courseids = collect.get(0).stream().map(UserCollection::getMainId).collect(Collectors.toList());
            //课程集合
            List<Course> courseList = courseService.getCourseAndDelete(courseids);
            //类别id集合
            List<Long> catIds = courseList.stream().map(Course::getCourseTypeId).collect(Collectors.toList());
//            //价格id集合
//            List<Integer> priceIds = courseList.stream().map(Course::getCoursePriceId).collect(Collectors.toList());
            //类别集合
            List<Category> categoryList = categoryService.list(new LambdaQueryWrapper<Category>().in(Category::getId, catIds));
//            //价格集合
//            List<SystemGroupData> systemGroupDataList = systemGroupDataService.list(new LambdaQueryWrapper<SystemGroupData>().in(SystemGroupData::getId, priceIds));


            //类别ID  类别map
            HashMap<Integer, Category> map = new HashMap<>();
            for (Category category : categoryList) {
                map.put(category.getId(), category);
            }
//            //价格id和价格map
//            HashMap<Integer, SystemGroupData> map1 = new HashMap<>();
//            for (SystemGroupData systemGroupData : systemGroupDataList) {
//                map1.put(systemGroupData.getId(),systemGroupData);
//            }
            //将类别 价格 和课程id对应放入map
            for (Course course : courseList) {
                courseMap.put(course.getId(), course);
                courseCatMap.put(course.getId(), map.get(course.getCourseTypeId().intValue()));
//                coursePriceMap.put(course.getId(),map1.get(course.getCoursePriceId()));
            }
        }
        //套课
        if (ObjectUtil.isNotNull(collect.get(1))) {
            List<Long> packageCourseids = collect.get(1).stream().map(UserCollection::getMainId).collect(Collectors.toList());
            //套课集合
            List<CoursePackage> coursePackageList = coursePackageService.getCoursePackagesAndDelete(packageCourseids);
            //类别id集合
            List<Integer> catIds = coursePackageList.stream().map(CoursePackage::getCourseTypeId).collect(Collectors.toList());
            //类别集合
            List<Category> categoryList = categoryService.list(new LambdaQueryWrapper<Category>().in(Category::getId, catIds));

            //类别ID  类别map
            HashMap<Integer, Category> map = new HashMap<>();
            for (Category category : categoryList) {
                map.put(category.getId(), category);
            }

            //将类别 价格 和课程id对应放入map
            for (CoursePackage coursePackage : coursePackageList) {
                packageCourseMap.put(coursePackage.getId(), coursePackage);
                packageCourseCatMap.put(coursePackage.getId(), map.get(coursePackage.getCourseTypeId()));
            }
        }
        //讲座
        if (ObjectUtil.isNotNull(collect.get(2))) {
            //讲座id集合
            List<Long> talkids = collect.get(2).stream().map(UserCollection::getMainId).collect(Collectors.toList());
            //讲座集合
            List<Talk> talkList = talkService.getTalksAndDelete(talkids);
            //讲座排期集合
            List<TalkScheduling> talkSchedulings = talkSchedulingService.list(new LambdaQueryWrapper<TalkScheduling>().in(TalkScheduling::getTalkId, talkids).orderByAsc(TalkScheduling::getSchedulingDate, TalkScheduling::getSchedulingStartTime));
            talkSchedulingMap = talkSchedulings.stream().collect(groupingBy(TalkScheduling::getTalkId));
            for (Talk talk : talkList) {
                talkMap.put(talk.getId(), talk);
            }

//            for (TalkScheduling talkScheduling : talkSchedulings) {
//                talkSchedulingMap.put(talkScheduling.getTalkId(),talkScheduling);
//            }
        }
        //展览
        if (ObjectUtil.isNotNull(collect.get(3))) {
            List<Long> exhibitionids = collect.get(3).stream().map(UserCollection::getMainId).collect(Collectors.toList());
            //展览集合
            List<Exhibition> exhibitionList = exhibitionService.getExhibitionsAndDelete(exhibitionids);
            for (Exhibition exhibition : exhibitionList) {
                exhibitionMap.put(exhibition.getId(), exhibition);
            }
        }
        //商品
        if (ObjectUtil.isNotNull(collect.get(4))) {
            List<Integer> productids = collect.get(4).stream().map(UserCollection::getProductId).collect(Collectors.toList());
            //商品集合
            List<VcaProduct> vcaProductList = vcaProductService.getProductsAndDelete(productids);
            //商品类别ids
            List<Integer> cids = vcaProductList.stream().map(VcaProduct::getCid).collect(Collectors.toList());
            //类别集合
            List<Category> categoryList = categoryService.list(new LambdaQueryWrapper<Category>().in(Category::getId, cids));

            //类别ID  类别map
            HashMap<Integer, Category> map = new HashMap<>();
            for (Category category : categoryList) {
                map.put(category.getId(), category);
            }

            //将类别 价格 和课程id对应放入map
            for (VcaProduct vcaProduct : vcaProductList) {
                productCatMap.put(vcaProduct.getId(), map.get(vcaProduct.getCid()));
                productMap.put(vcaProduct.getId(), vcaProduct);
            }
        }
        List<CollectionsResponse> collections = new ArrayList<>();
        for (UserCollection userCollection : userCollections) {
            CollectionsResponse collectionsResponse = new CollectionsResponse();
            if (userCollection.getMainType().equals(0)) {
                //课程
                Course course = courseMap.get(userCollection.getMainId());
                //类别
                Category category = courseCatMap.get(userCollection.getMainId());
                if (ObjectUtil.isNull(course) || ObjectUtil.isNull(category)) {
                    collections.add(collectionsResponse);
                    continue;
                }
                collectionsResponse.setId(userCollection.getMainId());
                collectionsResponse.setMainType(userCollection.getMainType());
                collectionsResponse.setImagePath(course.getCover());

                if("en".equals(language)){
                    collectionsResponse.setName(course.getNameEn());
                    collectionsResponse.setTagText(category.getNameEn());
                }else{
                    collectionsResponse.setName(course.getName());
                    collectionsResponse.setTagText(category.getName());
                }
                collectionsResponse.setThemeColor(category.getLabelColor());
                collectionsResponse.setAvailable(course.getStatus() ? 1 : 0);
                collectionsResponse.setIsDeleted(course.getIsDeleted().equals(1));
                collections.add(collectionsResponse);
            } else if (userCollection.getMainType().equals(1)) {
                Category category = packageCourseCatMap.get(userCollection.getMainId());
                CoursePackage coursePackage = packageCourseMap.get(userCollection.getMainId());
                if (ObjectUtil.isNull(coursePackage) || ObjectUtil.isNull(category)) {
                    collections.add(collectionsResponse);
                    continue;
                }
                collectionsResponse.setId(userCollection.getMainId());
                collectionsResponse.setMainType(userCollection.getMainType());
                collectionsResponse.setImagePath(coursePackage.getCoverImage());

                if("en".equals(language)){
                    collectionsResponse.setName(coursePackage.getNameEn());
                    collectionsResponse.setTagText(category.getNameEn());
                }else{
                    collectionsResponse.setName(coursePackage.getName());
                    collectionsResponse.setTagText(category.getName());
                }
                collectionsResponse.setThemeColor(category.getLabelColor());
                collectionsResponse.setAvailable(coursePackage.getStatus());
                collectionsResponse.setIsDeleted(coursePackage.getIsDeleted().equals(1));
                collections.add(collectionsResponse);
            } else if (userCollection.getMainType().equals(2)) {
                Talk talk = talkMap.get(userCollection.getMainId());
                List<TalkScheduling> talkSchedulings = talkSchedulingMap.get(userCollection.getMainId());
                if (ObjectUtil.isNull(talk) || CollUtil.isEmpty(talkSchedulings)) {
                    collections.add(collectionsResponse);
                    continue;
                }
                collectionsResponse.setId(userCollection.getMainId());
                collectionsResponse.setMainType(userCollection.getMainType());
                collectionsResponse.setImagePath(talk.getCoverImage());

                if("en".equals(language)){
                    collectionsResponse.setName(talk.getNameEn());
                    collectionsResponse.setTagText(talk.getTalkType().equals(1) ? "In-person Talk" : "Online Talk");
                }else{
                    collectionsResponse.setName(talk.getName());
                    collectionsResponse.setTagText(talk.getTalkType().equals(1) ? "线下讲座" : "线上讲座");
                }
                collectionsResponse.setThemeColor("#B4B19E");
                collectionsResponse.setAvailable(talk.getStatus());
                collectionsResponse.setIsDeleted(talk.getIsDeleted().equals(1));
                List<TalkScheduling> list_remove = new ArrayList<>();
                for (TalkScheduling talkScheduling : talkSchedulings) {
                    //当前排期状态（0=已过期 1=进行中 2=未开始）
                    Integer status = DateUtil.getSchedulingStatus(talkScheduling.getSchedulingDate(), talkScheduling.getSchedulingStartTime(), talkScheduling.getSchedulingEndTime());
                    if (status.equals(0)) {
                        list_remove.add(talkScheduling);
                    }
                }
                talkSchedulings.removeAll(list_remove);
                if (talkSchedulings.size() > 0) {
                    //排序
                    talkSchedulings.sort(Comparator.comparing(TalkScheduling::getSchedulingDate).thenComparing(TalkScheduling::getSchedulingStartTime));
                    collectionsResponse.setDate(talkSchedulings.get(0).getSchedulingDate());
                    collectionsResponse.setStartTime(talkSchedulings.get(0).getSchedulingStartTime());
                    collectionsResponse.setEndTime(talkSchedulings.get(0).getSchedulingEndTime());
                }
                collections.add(collectionsResponse);
            } else if (userCollection.getMainType().equals(3)) {
                Exhibition exhibition = exhibitionMap.get(userCollection.getMainId());
                if (ObjectUtil.isNull(exhibition)) {
                    collections.add(collectionsResponse);
                    continue;
                }
                collectionsResponse.setId(userCollection.getMainId());
                collectionsResponse.setMainType(userCollection.getMainType());
                collectionsResponse.setImagePath(exhibition.getCover());

                if("en".equals(language)){
                    collectionsResponse.setName(exhibition.getNameEn());
                    collectionsResponse.setTagText("Exhibiton");
                }else{
                    collectionsResponse.setName(exhibition.getName());
                    collectionsResponse.setTagText("展览");
                }
                collectionsResponse.setThemeColor("#8C734A");
                collectionsResponse.setAvailable(exhibition.getStatus());
                collectionsResponse.setIsDeleted(exhibition.getIsDeleted().equals(1));
                collectionsResponse.setStartDate(DateUtil.dateToStr(exhibition.getStartTime(), Constants.DATE_FORMAT_DATE));
                collectionsResponse.setEndDate(DateUtil.dateToStr(exhibition.getEndTime(), Constants.DATE_FORMAT_DATE));
                collections.add(collectionsResponse);
            } else if (userCollection.getMainType().equals(4)) {
                Category category = productCatMap.get(userCollection.getProductId());
                VcaProduct vcaProduct = productMap.get(userCollection.getProductId());
                if (ObjectUtil.isNull(category) || ObjectUtil.isNull(vcaProduct)) {
                    collections.add(collectionsResponse);
                    continue;
                }
                collectionsResponse.setProductId(userCollection.getProductId());
                collectionsResponse.setMainType(userCollection.getMainType());
                collectionsResponse.setImagePath(vcaProduct.getCoverImage());

                if("en".equals(language)){
                    collectionsResponse.setName(vcaProduct.getNameEn());
                    collectionsResponse.setTagText(category.getNameEn());
                }else{
                    collectionsResponse.setName(vcaProduct.getName());
                    collectionsResponse.setTagText(category.getName());
                }
                collectionsResponse.setThemeColor(category.getLabelColor());
                collectionsResponse.setAvailable(vcaProduct.getIsShow() ? 1 : 0);
                collectionsResponse.setIsDeleted(vcaProduct.getIsDeleted());
                collections.add(collectionsResponse);
            }
        }
//        List<CollectionsResponse> collections = new ArrayList<>();
//        if (CollUtil.isEmpty(getCollections(userCollections))) {
//            return CommonPage.copyPageInfo(page, collections);
//        }
//        collections = getCollections(userCollections);
        return CommonPage.copyPageInfo(page, collections);
    }

    /**
     * @param phone
     * @Description:根据手机号查询用户
     * @Author: chenBing
     * @Date: 2022/10/8
     */
    @Override
    public User getByPhone(String phone) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone, phone);
        return userDao.selectOne(lqw);
    }

    /**
     * @param thirdUserRequest 三方用户登录注册信息
     * @Description:通过微信信息注册用户
     * @Author: chenBing
     * @Date: 2022/10/8
     */
    @Override
    public User registerByThird(RegisterThirdUserRequest thirdUserRequest) {
        User user = new User();
        user.setAccount(DigestUtils.md5Hex(VcaUtil.getUuid() + DateUtil.getNowTime()));
        user.setUserType(thirdUserRequest.getType());
        user.setNickname(thirdUserRequest.getNickName());
        String avatar = null;
        switch (thirdUserRequest.getType()) {
            case Constants.USER_LOGIN_TYPE_PUBLIC:
                avatar = thirdUserRequest.getHeadimgurl();
                break;
            case Constants.USER_LOGIN_TYPE_PROGRAM:
            case Constants.USER_LOGIN_TYPE_H5:
            case Constants.USER_LOGIN_TYPE_IOS_WX:
            case Constants.USER_LOGIN_TYPE_ANDROID_WX:
                avatar = thirdUserRequest.getAvatar();
                break;
            default:
                break;
        }
        user.setAvatar(avatar);
        if (StringUtils.isNotBlank(thirdUserRequest.getUnionId())) {
            user.setUnionId(thirdUserRequest.getUnionId());
        }
        return user;
    }

    /**
     * @Description:获取个人资料
     * @Author: chenBing
     * @Date: 2022/10/8
     */
    @Override
    public User getInfoException() {
        User user = getInfo();
        if (user == null) {
            throw new VcaException("用户信息不存在！");
        }

        if (!user.getStatus()) {
            throw new VcaException("用户已经被禁用！");
        }
        return user;
    }

    /**
     * @Description:获取个人资料
     * @Author: chenBing
     * @Date: 2022/10/8
     */
    @Override
    public User getInfo() {
        if (getUserId() == 0) {
            return null;
        }
        return getById(getUserId());
    }

    /**
     * @Description:获取当前用户id
     * @Author: chenBing
     * @Date: 2022/10/8
     */
    @Override
    public Integer getUserId() {
        Integer id = tokenComponet.getUserId();
        if (null == id) {
            return 0;
        }
        return id;
    }

    /**
     * @param userIds
     * @Description:根据用户id获取用户列表 map模式
     * @Author: chenBing
     * @Date: 2022/10/8
     */
    @Override
    public HashMap<Integer, User> getMapListInUid(List<Integer> userIds) {
        List<User> userList = getListInUid(userIds);
        return getMapByList(userList);
    }

    /**
     * @return HashMap<Integer, User>
     * @Description: 用户id in list
     * @author Mr.Zhang
     * @since 2020-04-28
     */
    private List<User> getListInUid(List<Integer> uidList) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(User::getUid, uidList);
        return userDao.selectList(lambdaQueryWrapper);
    }

    /**
     * 根据用户id获取用户列表 map模式
     *
     * @return HashMap<Integer, User>
     * @author Mr.Zhang
     * @since 2020-04-28
     */
    private HashMap<Integer, User> getMapByList(List<User> list) {
        HashMap<Integer, User> map = new HashMap<>();
        if (null == list || list.size() < 1) {
            return map;
        }
        for (User user : list) {
            map.put(user.getUid(), user);
        }
        return map;
    }

    /**
     * 清除User Group id
     *
     * @param groupId 待清除的GroupId
     */
    @Override
    public void clearGroupByGroupId(String groupId) {
        LambdaUpdateWrapper<User> upw = Wrappers.lambdaUpdate();
        update(upw);
    }

    /**
     * 分页显示用户表
     *
     * @param request          搜索条件
     * @param pageParamRequest 分页参数
     */
    @Override
    public PageInfo<UserResponse> getList(UserSearchRequest request, PageParamRequest pageParamRequest) {
        Page<User> pageUser = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Map<String, Object> map = new HashMap<>();

        if (ObjectUtil.isNotEmpty(request.getUserRegisterType())) {
            map.put("userRegisterType", request.getUserRegisterType());
        }

        if (StringUtils.isNotBlank(request.getUserType())) {
            map.put("userType", request.getUserType());
        }

        if (StringUtils.isNotBlank(request.getSex())) {
            lambdaQueryWrapper.eq(User::getSex, request.getSex());
            map.put("sex", Integer.valueOf(request.getSex()));
        }

        if (request.getStatus() != null) {
            map.put("status", request.getStatus() ? 1 : 0);
        }

        dateLimitUtilVo dateLimit = DateUtil.getDateLimit(request.getDateLimit());

        if (!StringUtils.isBlank(dateLimit.getStartTime())) {
            map.put("startTime", dateLimit.getStartTime());
            map.put("endTime", dateLimit.getEndTime());
            map.put("accessType", request.getAccessType());
        }
        if (ObjectUtil.isNotEmpty(request.getKeywords())) {
            map.put("keywords", request.getKeywords());
        }
        List<User> userList = userDao.findAdminList(map);
        List<UserResponse> userResponses = new ArrayList<>();
        for (User user : userList) {
            UserResponse userResponse = new UserResponse();
            if (user.getUserRegisterType() == 1) {
                UserAddress address = userAddressService.getOne(new LambdaQueryWrapper<UserAddress>().eq(UserAddress::getUid, user.getUid()).eq(UserAddress::getIsDefault, Boolean.TRUE));
                if (ObjectUtil.isNotEmpty(address)) {
                    userResponse.setAddres(address.getProvince() + address.getCity() + address.getDistrict() + address.getDetail());
                }
            }
            BeanUtils.copyProperties(user, userResponse);
            // 获取分组信息
//            if (!StringUtils.isBlank(user.getGroupId())) {
//                userResponse.setGroupName(userGroupService.getGroupNameInId(user.getGroupId()));
//                userResponse.setGroupId(user.getGroupId());
//            }
//
//            // 获取标签信息
//            if (!StringUtils.isBlank(user.getTagId())) {
//                userResponse.setTagName(userTagService.getGroupNameInId(user.getTagId()));
//                userResponse.setTagId(user.getTagId());
//            }

            userResponse.setPhone(VcaUtil.maskMobile(userResponse.getPhone()));
            userResponses.add(userResponse);
        }
        return CommonPage.copyPageInfo(pageUser, userResponses);
    }

    @Override
    public List<User> getList(UserSearchRequest request) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Map<String, Object> map = new HashMap<>();

        if (ObjectUtil.isNotEmpty(request.getUserRegisterType())) {
            map.put("userRegisterType", request.getUserRegisterType());
        }

        if (StringUtils.isNotBlank(request.getUserType())) {
            map.put("userType", request.getUserType());
        }

        if (StringUtils.isNotBlank(request.getSex())) {
            lambdaQueryWrapper.eq(User::getSex, request.getSex());
            map.put("sex", Integer.valueOf(request.getSex()));
        }

        if (request.getStatus() != null) {
            map.put("status", request.getStatus() ? 1 : 0);
        }

        dateLimitUtilVo dateLimit = DateUtil.getDateLimit(request.getDateLimit());

        if (!StringUtils.isBlank(dateLimit.getStartTime())) {
            map.put("startTime", dateLimit.getStartTime());
            map.put("endTime", dateLimit.getEndTime());
            map.put("accessType", request.getAccessType());
        }
        if (ObjectUtil.isNotEmpty(request.getKeywords())) {
            map.put("keywords", request.getKeywords());
        }
        return userDao.findAdminList(map);
    }

    /**
     * 更新用户
     *
     * @param userRequest 用户参数
     * @return Boolean
     */
    @Override
    public Boolean updateUser(UserUpdateRequest userRequest) {
        User tempUser = getById(userRequest.getUid());
        User user = new User();
        BeanUtils.copyProperties(userRequest, user);
        return updateById(user);
    }

    /**
     * 后台修改用户手机号
     *
     * @param id    用户uid
     * @param phone 手机号
     * @return Boolean
     */
    @Override
    public Boolean updateUserPhone(Integer id, String phone) {
        boolean matchPhone = ReUtil.isMatch(RegularConstants.PHONE_TWO, phone);
        if (!matchPhone) {
            throw new VcaException("手机号格式错误，请输入正确得手机号");
        }
        User user = getById(id);
        if (ObjectUtil.isNull(user)) {
            throw new VcaException("对应用户不存在");
        }
        if (phone.equals(user.getPhone())) {
            throw new VcaException("手机号与之前一致");
        }

        //检测当前手机号是否已经是账号
        User tempUser = getByPhone(phone);
        if (ObjectUtil.isNotNull(tempUser)) {
            throw new VcaException("此手机号码已被注册");
        }

        User newUser = new User();
        newUser.setUid(id);
        newUser.setPhone(phone);
        newUser.setAccount(phone);
        return userDao.updateById(newUser) > 0;
    }

    /**
     * 获取用户详情
     *
     * @param id 用户uid
     */
    @Override
    public User getInfoByUid(Integer id) {
        User user = getById(id);
        if (ObjectUtil.isNull(user)) {
            throw new VcaException("用户不存在");
        }
        return user;
    }

    /**
     * 操作积分、余额
     */
    @Override
    public Boolean updateIntegralMoney(UserOperateIntegralMoneyRequest request) {
        if (ObjectUtil.isNull(request.getMoneyValue()) || ObjectUtil.isNull(request.getIntegralValue())) {
            throw new VcaException("至少输入一个金额");
        }
        if (request.getMoneyValue().compareTo(BigDecimal.ZERO) < 1 && request.getIntegralValue() <= 0) {
            throw new VcaException("修改值不能等小于等于0");
        }

        User user = getById(request.getUid());
        if (ObjectUtil.isNull(user)) {
            throw new VcaException("用户不存在");
        }
        // 减少时要判断小于0的情况,添加时判断是否超过数据限制
        if (request.getMoneyType().equals(2) && request.getMoneyValue().compareTo(BigDecimal.ZERO) != 0) {
            if (user.getNowMoney().subtract(request.getMoneyValue()).compareTo(BigDecimal.ZERO) < 0) {
                throw new VcaException("余额扣减后不能小于0");
            }
        }
        if (request.getMoneyType().equals(1) && request.getMoneyValue().compareTo(BigDecimal.ZERO) != 0) {
            if (user.getNowMoney().add(request.getMoneyValue()).compareTo(new BigDecimal("99999999.99")) > 0) {
                throw new VcaException("余额添加后后不能大于99999999.99");
            }
        }

        if (request.getIntegralType().equals(2) && request.getIntegralValue() != 0) {
            if (user.getIntegral() - request.getIntegralValue() < 0) {
                throw new VcaException("积分扣减后不能小于0");
            }
        }
        if (request.getIntegralType().equals(1) && request.getIntegralValue() != 0) {
            if ((user.getIntegral() + request.getIntegralValue()) > 99999999) {
                throw new VcaException("积分添加后不能大于99999999");
            }
        }

        Boolean execute = transactionTemplate.execute(e -> {
            // 处理余额
            if (request.getMoneyValue().compareTo(BigDecimal.ZERO) > 0) {
                // 生成UserBill
                UserBill userBill = new UserBill();
                userBill.setUid(user.getUid());
                userBill.setLinkId("0");
                userBill.setTitle("后台操作");
                userBill.setCategory(Constants.USER_BILL_CATEGORY_MONEY);
                userBill.setNumber(request.getMoneyValue());
                userBill.setStatus(1);
                userBill.setCreateTime(DateUtil.nowDateTime());

                if (request.getMoneyType() == 1) {// 增加
                    userBill.setPm(1);
                    userBill.setType(Constants.USER_BILL_TYPE_SYSTEM_ADD);
                    userBill.setBalance(user.getNowMoney().add(request.getMoneyValue()));
                    userBill.setMark(StrUtil.format("后台操作增加了{}余额", request.getMoneyValue()));

                    userBillService.save(userBill);
                    operationNowMoney(user.getUid(), request.getMoneyValue(), user.getNowMoney(), "add");
                } else {
                    userBill.setPm(0);
                    userBill.setType(Constants.USER_BILL_TYPE_SYSTEM_SUB);
                    userBill.setBalance(user.getNowMoney().subtract(request.getMoneyValue()));
                    userBill.setMark(StrUtil.format("后台操作减少了{}余额", request.getMoneyValue()));

                    userBillService.save(userBill);
                    operationNowMoney(user.getUid(), request.getMoneyValue(), user.getNowMoney(), "sub");
                }
            }

            // 处理积分
            if (request.getIntegralValue() > 0) {
                // 生成记录
                UserIntegralRecord integralRecord = new UserIntegralRecord();
                integralRecord.setUid(user.getUid());
                integralRecord.setLinkType(IntegralRecordConstants.INTEGRAL_RECORD_LINK_TYPE_SIGN);
                integralRecord.setTitle(IntegralRecordConstants.BROKERAGE_RECORD_TITLE_SYSTEM);
                integralRecord.setIntegral(request.getIntegralValue());
                integralRecord.setStatus(IntegralRecordConstants.INTEGRAL_RECORD_STATUS_COMPLETE);
                if (request.getIntegralType() == 1) {// 增加
                    integralRecord.setType(IntegralRecordConstants.INTEGRAL_RECORD_TYPE_ADD);
                    integralRecord.setBalance(user.getIntegral() + request.getIntegralValue());
                    integralRecord.setMark(StrUtil.format("后台操作增加了{}积分", request.getIntegralValue()));

                    operationIntegral(user.getUid(), request.getIntegralValue(), user.getIntegral(), "add");
                } else {
                    integralRecord.setType(IntegralRecordConstants.INTEGRAL_RECORD_TYPE_SUB);
                    integralRecord.setBalance(user.getIntegral() - request.getIntegralValue());
                    integralRecord.setMark(StrUtil.format("后台操作减少了{}积分", request.getIntegralValue()));
                    operationIntegral(user.getUid(), request.getIntegralValue(), user.getIntegral(), "sub");
                }
                userIntegralRecordService.save(integralRecord);
            }
            return Boolean.TRUE;
        });

        if (!execute) {
            throw new VcaException("修改积分/余额失败");
        }
        return execute;
    }

    /**
     * 添加/扣减积分
     *
     * @param uid         用户id
     * @param integral    积分
     * @param nowIntegral 历史积分
     * @param type        类型：add—添加，sub—扣减
     * @return Boolean
     */
    @Override
    public Boolean operationIntegral(Integer uid, Integer integral, Integer nowIntegral, String type) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        if (type.equals("add")) {
            updateWrapper.setSql(StrUtil.format("integral = integral + {}", integral));
        } else {
            updateWrapper.setSql(StrUtil.format("integral = integral - {}", integral));
            updateWrapper.last(StrUtil.format(" and (integral - {} >= 0)", integral));
        }
        updateWrapper.eq("uid", uid);
        updateWrapper.eq("integral", nowIntegral);
        return update(updateWrapper);
    }

    /**
     * 根据昵称匹配用户，返回id集合
     *
     * @param nikeName 需要匹配得昵称
     * @return List
     */
    @Override
    public List<Integer> findIdListLikeName(String nikeName) {
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.select(User::getUid);
        lqw.like(User::getNickname, nikeName);
        List<User> userList = userDao.selectList(lqw);
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(User::getUid).collect(Collectors.toList());
    }

    /**
     * 获取当前用户id
     *
     * @return Integer
     */
    @Override
    public Integer getUserIdException() {
        Integer id = tokenComponet.getUserId();
        if (null == id) {
//            throw new VcaException("登录信息已过期，请重新登录！");
            throw new VcaException(ExceptionCodeEnum.UNAUTHORIZED.getMessage());
        }
        return id;
    }

    /**
     * 检测手机验证码key
     *
     * @param phone String 手机号
     * @return String
     */
    @Override
    public String getValidateCodeRedisKey(String phone) {
        return SmsConstants.SMS_VALIDATE_PHONE + phone;
    }

    /**
     * 检测手机验证码
     */
    private void checkValidateCode(String phone, String value) {
        Object validateCode = redisUtil.get(getValidateCodeRedisKey(phone));
        if (validateCode == null) {
            throw new VcaException("验证码已过期");
        }

        if (!validateCode.toString().equals(value)) {
            throw new VcaException("验证码错误");
        }
    }

    /**
     * 添加内部员工
     *
     * @param request
     * @return 成功 失败
     * @author Li
     * @date 2022/11/09 11:08
     */
    @Override
    public boolean addInternalUser(UserAddInternalRequest request) {
        User user = new User();
        Date date = DateUtil.nowDateTime();
        user.setCreateTime(date);
        if (ObjectUtil.isEmpty(request.getPhone())) {
            throw new VcaException("内部员工手机号不可为空");
        }
        if (ObjectUtil.isEmpty(request.getNickName())) {
            throw new VcaException("内部员工昵称不可为空");
        }
       /* if (!ReUtil.isMatch(RegularConstants.EMAIL, request.getEmail())) {
            throw new VcaException("邮箱格式不对");
        }*/
        user.setAccount(request.getEmail());
        if (ObjectUtil.isNotEmpty(request.getPhone())) {
            if (!ReUtil.isMatch(RegularConstants.PHONE_TWO, request.getPhone())) {
                throw new VcaException("手机号格式不对");
            }
            if (ObjectUtil.isNotEmpty(getByPhone(request.getPhone()))) {
                throw new VcaException("当前手机号已被注册");
            }
            user.setPhone(request.getPhone());
            user.setAccount(request.getPhone());
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper();
        wrapper.eq(User::getEmail, request.getEmail());
        if (ObjectUtil.isNotEmpty(userDao.selectOne(wrapper))) {
            throw new VcaException("当前邮箱已注册");
        }
        user.setEmail(request.getEmail());
        user.setNickname(request.getNickName());
        user.setStatus(request.getStatus());
        user.setUserType("routine");
        user.setLoginType("routine");
        user.setUserRegisterType(2);
        if (ObjectUtil.isNotEmpty(request.getAvatar())) {
            user.setAvatar(systemAttachmentService.clearPrefix(request.getAvatar()));
        }
        return transactionTemplate.execute(e -> {
            userDao.insert(user);
            return Boolean.TRUE;
        });
    }

    /**
     * 修改用户邮箱
     *
     * @param id    用户uid
     * @param email 手机号
     * @author Li
     * @date 2022/11/09 13:13
     */
    @Override
    public boolean updateUserEmail(Integer id, String email) {
        if (ObjectUtil.isEmpty(id)) {
            throw new VcaException("用户id不可为空");
        }
        if (ObjectUtil.isEmpty(email)) {
            throw new VcaException("用户email不可为空");
        }
        if (!ReUtil.isMatch(RegularConstants.EMAIL, email)) {
            throw new VcaException("邮箱格式不对");
        }
        User user = userDao.selectById(id);
        if (ObjectUtil.isEmpty(user)) {
            throw new VcaException("该用户不存在");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper();
        wrapper.eq(User::getEmail, email);
        if (ObjectUtil.isNotEmpty(userDao.selectOne(wrapper))) {
            throw new VcaException("当前邮箱已注册");
        }
        user.setEmail(email);
        return transactionTemplate.execute(e -> {
            userDao.updateById(user);
            return Boolean.TRUE;
        });
    }

    /**
     * 获取用户的消费记录
     *
     * @param id
     * @param pageParamRequest
     * @return
     * @author Li
     * @date 2022/11/09 13:16
     */
    @Override
    public PageInfo getExpenseCalendar(Integer id, PageParamRequest pageParamRequest) {
        if (ObjectUtil.isEmpty(id)) {
            throw new VcaException("用户id不可为空");
        }
        Page<UserExpenseCalendarResponse> pageOrder = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<StoreOrder> orders = storeOrderDao.selectList(new LambdaQueryWrapper<StoreOrder>().eq(StoreOrder::getUid, id).eq(StoreOrder::getIsDel, 0).ne(StoreOrder::getRefundStatus, 3).eq(StoreOrder::getPaid, 1));
        List<UserExpenseCalendarResponse> responses = new ArrayList<>();
        orders.forEach(e -> {
            UserExpenseCalendarResponse response = new UserExpenseCalendarResponse();
            BeanUtils.copyProperties(e, response);
            List<StoreOrderInfo> orderInfos = storeOrderInfoService.list(new LambdaQueryWrapper<StoreOrderInfo>().eq(StoreOrderInfo::getOrderNo, e.getOrderId()).eq(StoreOrderInfo::getRefundStatus, 0));
            if (ObjectUtil.isNotEmpty(orderInfos)) {

                StoreOrderInfo storeOrderInfo = orderInfos.get(0);
                switch (storeOrderInfo.getType()) {
                    case 0:
                        response.setType("课程订单");
                        break;
                    case 1:
                        response.setType("套课订单");
                        break;
                    case 2:
                        response.setType("讲座订单");
                        break;
                    case 3:
                        response.setType("展览订单");
                        break;
                    case 4:
                        response.setType("商品订单");
                        break;
                    default:
                        break;
                }
                response.setPayNum(orderInfos.stream().mapToInt(StoreOrderInfo::getPayNum).sum());
            } else {
                response.setType("未知订单");
                response.setPayNum(0);
            }
            responses.add(response);
        });
        return CommonPage.copyPageInfo(pageOrder, responses);
    }

    /**
     * 获取用户总订单详情
     *
     * @param id
     * @return
     * @author Li
     * @date 2022/11/09 16:32
     */
    @Override
    public Map<String, Object> getUserOrderInfo(Integer id) {
        if (ObjectUtil.isEmpty(id)) {
            throw new VcaException("用户id不可为空");
        }
        Map<String, Object> map = new HashMap<>();
        List<StoreOrder> orders = storeOrderDao.getMonthIsCompleteOrder(id);
        LambdaQueryWrapper<StoreOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StoreOrder::getUid, id);
        wrapper.ne(StoreOrder::getRefundStatus, 3);
        wrapper.eq(StoreOrder::getIsDel, 0);
        wrapper.eq(StoreOrder::getPaid, 1);
        int totalOrder = storeOrderDao.selectList(wrapper).size();
        map.put("totalOrder", ObjectUtil.isNotEmpty(totalOrder) ? totalOrder : 0);
        BigDecimal totalPrice = storeOrderDao.getTotalPrice("uid= " + id);
        map.put("totalPrice", ObjectUtil.isEmpty(totalPrice) ? 0 : totalPrice);
        map.put("monthOrder", ObjectUtil.isNotEmpty(orders) ? orders.size() : 0);
        BigDecimal monthPrice = storeOrderDao.getTotalPrice("uid= " + id + " AND DATE_FORMAT( create_time, '%Y-%m' ) = DATE_FORMAT( now( ), '%Y-%m' )");
        map.put("monthPrice", ObjectUtil.isEmpty(monthPrice) ? 0 : monthPrice);
        String code = "userid=" + id.toString() + "&channel=wechat&time=" + System.currentTimeMillis();
        String qrCode = MiracleAECUtil.encrypt(code);
        map.put("qrCode", qrCode);
        return map;
    }

    /**
     * @Description:礼品卡接受赠送
     * @author:chenbing
     * @date 2022/12/1 19:44
     */
    @Override
    public boolean getCardToSend(Integer sendUser, String cardNo) {
        User user = getInfoException();
        UserCard userCard = userCardService.getOne(new LambdaQueryWrapper<UserCard>().eq(UserCard::getCardNo, cardNo)
                .eq(UserCard::getUid, sendUser).eq(UserCard::getStutus, 0));
        if (userCard == null) {
            throw new VcaException("当前赠送链接失效或已被他人领取");
        }
        if (userCard.getUid().equals(user.getUid())) {
            throw new VcaException("不能领取自己的礼品卡");
        }
        StoreOrderInfo orderInfo = storeOrderInfoService.getOne(new LambdaQueryWrapper<StoreOrderInfo>().eq(StoreOrderInfo::getMerOrderNo, userCard.getOrderId()));
        if (orderInfo != null) {
            StoreOrder storeOrder = vcaOrderService.getOne(new LambdaQueryWrapper<StoreOrder>().eq(StoreOrder::getOrderId, orderInfo.getOrderNo()));
            Integer uid = storeOrder.getUid();
            if (!Objects.equals(uid, userCard.getUid())) {
                throw new VcaException("礼品卡不能进行二次赠送");
            }
        }
        userCard.setUid(user.getUid());
        // TODO: 2022/12/1  增加礼品卡赠送日志
        VcaUserCardRecord vcaUserCardRecord = new VcaUserCardRecord();
        vcaUserCardRecord.setGetUser(user.getUid());
        vcaUserCardRecord.setSendUser(sendUser);
        vcaUserCardRecord.setCardId(userCard.getCardId());
        vcaUserCardRecord.setDescription(getById(sendUser).getNickname() + "赠送一张礼品卡给" + user.getNickname());
        vcaUserCardRecord.setCreateTime(new Date());
        Boolean execute = transactionTemplate.execute(e -> {
            userCardService.updateById(userCard);
            vcaUserCardRecordService.save(vcaUserCardRecord);
            return Boolean.TRUE;
        });
        if (!execute) {
            throw new VcaException("领取失败");
        }
        return true;
    }

    /**
     * 添加/扣减余额
     *
     * @param uid      用户id
     * @param price    金额
     * @param nowMoney 历史金额
     * @param type     类型：add—添加，sub—扣减
     */
    @Override
    public Boolean operationNowMoney(Integer uid, BigDecimal price, BigDecimal nowMoney, String type) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        if (type.equals("add")) {
            updateWrapper.setSql(StrUtil.format("now_money = now_money + {}", price));
        } else {
            updateWrapper.setSql(StrUtil.format("now_money = now_money - {}", price));
            updateWrapper.last(StrUtil.format(" and (now_money - {} >= 0)", price));
        }
        updateWrapper.eq("uid", uid);
        updateWrapper.eq("now_money", nowMoney);
        return update(updateWrapper);
    }

    /**
     * 类型:0-课程 1=套课 2=讲座 3=展览 4=商品
     *
     * @param
     * @return
     */
//    public List<CollectionsResponse> getCollections(List<UserCollection> userCollections) {
//
//        if (CollUtil.isEmpty(userCollections)) {
//            return null;
//        }
//        ArrayList<CollectionsResponse> collectionsResponseArrayList = new ArrayList<>();
//        userCollections.forEach(e -> {
//            if (e.getMainType().equals(0)) {
//                //课程
//                LambdaQueryWrapper<Course> courseLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                courseLambdaQueryWrapper.eq(Course::getId, e.getMainId());
//                courseLambdaQueryWrapper.eq(Course::getIsDeleted, false);
//                Course course = courseDao.selectOne(courseLambdaQueryWrapper);
//                if (ObjectUtil.isNull(course)) {
//                    throw new VcaException("该课程不存在 id: " + e.getMainId());
//                }
//                //类别
//                LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                categoryLambdaQueryWrapper.eq(Category::getId, course.getCourseTypeId());
//                categoryLambdaQueryWrapper.eq(Category::getIsDel, false);
//                Category category = categoryDao.selectOne(categoryLambdaQueryWrapper);
//                if (ObjectUtil.isNull(category)) {
//                    throw new VcaException("该类别不存在 id: " + course.getCourseTypeId());
//                }
//                //价格
//                SystemGroupData systemGroupData = systemGroupDataDao.selectById(course.getCoursePriceId());
//                String value = systemGroupData.getValue();
//                JSONObject jsonObject = JSONObject.parseObject(value);
//                JSONArray fields = (JSONArray) jsonObject.get("fields");
//                JSONObject object = (JSONObject) fields.get(0);
//                BigDecimal Price = new BigDecimal(object.get("value").toString());
//                CollectionsResponse collectionsResponse = new CollectionsResponse();
//
//                collectionsResponse.setMainId(e.getMainId());
//                collectionsResponse.setLabelColor(category.getLabelColor());
//                collectionsResponse.setCategoryName(category.getName());
//                collectionsResponse.setName(course.getName());
//                collectionsResponse.setImage(course.getCover());
//                collectionsResponse.setMainType(e.getMainType());
////                collectionsResponse.setPrice(Price);
////                collectionsResponse.setCreateTime(e.getCreateTime());
//                collectionsResponseArrayList.add(collectionsResponse);
//
//            } else if (e.getMainType().equals(1)) {
//                //套课
//                LambdaQueryWrapper<CoursePackage> coursePackageLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                coursePackageLambdaQueryWrapper.eq(CoursePackage::getId, e.getMainId());
//                coursePackageLambdaQueryWrapper.eq(CoursePackage::getIsDeleted, false);
//                CoursePackage coursePackage = coursePackageDao.selectOne(coursePackageLambdaQueryWrapper);
//                if (ObjectUtil.isNull(coursePackage)) {
//                    throw new VcaException("该套课不存在 id: " + e.getMainId());
//                }
//                //类别
//                LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                categoryLambdaQueryWrapper.eq(Category::getId, coursePackage.getCourseTypeId());
//                categoryLambdaQueryWrapper.eq(Category::getIsDel, false);
//                Category category = categoryDao.selectOne(categoryLambdaQueryWrapper);
//                if (ObjectUtil.isNull(category)) {
//                    throw new VcaException("该类别不存在 id: " + coursePackage.getCourseTypeId());
//                }
//                //价格
//                SystemGroupData systemGroupData = systemGroupDataDao.selectById(coursePackage.getCoursePackagePriceId());
//                String value = systemGroupData.getValue();
//                JSONObject jsonObject = JSONObject.parseObject(value);
//                JSONArray fields = (JSONArray) jsonObject.get("fields");
//                JSONObject object = (JSONObject) fields.get(0);
//                BigDecimal Price = new BigDecimal(object.get("value").toString());
//
//                CollectionsResponse collectionsResponse = new CollectionsResponse();
//                collectionsResponse.setMainId(e.getMainId());
//                collectionsResponse.setLabelColor(category.getLabelColor());
//                collectionsResponse.setCategoryName(category.getName());
//                collectionsResponse.setName(coursePackage.getName());
//                collectionsResponse.setImage(coursePackage.getCoverImage());
//                collectionsResponse.setMainType(e.getMainType());
////                collectionsResponse.setPrice(Price);
////                collectionsResponse.setCreateTime(e.getCreateTime());
//                collectionsResponseArrayList.add(collectionsResponse);
//            } else if (e.getMainType().equals(2)) {
//                //讲座
//                LambdaQueryWrapper<Talk> talkLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                talkLambdaQueryWrapper.eq(Talk::getId, e.getMainId());
//                talkLambdaQueryWrapper.eq(Talk::getIsDeleted, false);
//                Talk talk = talkDao.selectOne(talkLambdaQueryWrapper);
//                if (ObjectUtil.isNull(talk)) {
//                    throw new VcaException("该讲座不存在 id: " + e.getMainId());
//                }
//
//                CollectionsResponse collectionsResponse = new CollectionsResponse();
//                collectionsResponse.setLabelColor("#B4B19E");
//                collectionsResponse.setCategoryName(talk.getTalkType() == 1 ? "线下讲座" : "线上讲座");
//                collectionsResponse.setName(talk.getName());
//                collectionsResponse.setImage(talk.getCoverImage());
//                collectionsResponse.setMainType(e.getMainType());
////                collectionsResponse.setPrice(new BigDecimal(talk.getPrice()));
////                collectionsResponse.setCreateTime(e.getCreateTime());
//                collectionsResponseArrayList.add(collectionsResponse);
//            } else if (e.getMainType().equals(3)) {
//                //展览
//                LambdaQueryWrapper<Exhibition> exhibitionLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                exhibitionLambdaQueryWrapper.eq(Exhibition::getId, e.getMainId());
//                exhibitionLambdaQueryWrapper.eq(Exhibition::getIsDeleted, false);
//                Exhibition exhibition = exhibitionDao.selectOne(exhibitionLambdaQueryWrapper);
//                if (ObjectUtil.isNull(exhibition)) {
//                    throw new VcaException("该展览不存在 id: " + e.getMainId());
//                }
//
//                CollectionsResponse collectionsResponse = new CollectionsResponse();
//                collectionsResponse.setMainId(e.getMainId());
//                collectionsResponse.setName(exhibition.getName());
//                collectionsResponse.setImage(exhibition.getCover());
////                collectionsResponse.setPrice(new BigDecimal(exhibition.getPrice()));
//                collectionsResponse.setMainType(e.getMainType());
////                collectionsResponse.setCreateTime(e.getCreateTime());
//                collectionsResponseArrayList.add(collectionsResponse);
//            } else if (e.getMainType().equals(4)) {
//                //商品
//                LambdaQueryWrapper<VcaProduct> productLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                productLambdaQueryWrapper.eq(VcaProduct::getId, e.getProductId());
//                productLambdaQueryWrapper.eq(VcaProduct::getIsDeleted, false);
//                VcaProduct product = vcaProductDao.selectOne(productLambdaQueryWrapper);
//                if (ObjectUtil.isNull(product)) {
//                    throw new VcaException("该商品不存在 id: " + e.getProductId());
//                }
//                //类别
//                LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                categoryLambdaQueryWrapper.eq(Category::getId, product.getCid());
//                categoryLambdaQueryWrapper.eq(Category::getIsDel, false);
//                Category category = categoryDao.selectOne(categoryLambdaQueryWrapper);
//                if (ObjectUtil.isNull(category)) {
//                    throw new VcaException("该类别不存在 id: " + product.getCid());
//                }
//
//                CollectionsResponse collectionsResponse = new CollectionsResponse();
//                collectionsResponse.setProductId(e.getProductId());
//                collectionsResponse.setLabelColor(category.getLabelColor());
//                collectionsResponse.setCategoryName(category.getName());
//                collectionsResponse.setName(product.getName());
//                collectionsResponse.setImage(product.getImage());
//                collectionsResponse.setMainType(e.getMainType());
////                collectionsResponse.setPrice(product.getPrice());
////                collectionsResponse.setCreateTime(e.getCreateTime());
//                collectionsResponseArrayList.add(collectionsResponse);
//            }
//        });
//        return collectionsResponseArrayList;
//    }


    //根据id查询 课程 类型颜色
    public Map<Long, Category> getAppointmentList(List<Long> id) {
        HashMap<Long, Category> map = new HashMap<>();
        if (id.size() < 1) {
            return map;
        }
        LambdaQueryWrapper<Course> courseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseLambdaQueryWrapper.in(Course::getId, id);
        courseLambdaQueryWrapper.eq(Course::getIsDeleted, false);
        List<Course> courses = courseDao.selectList(courseLambdaQueryWrapper);
        List<Long> collectId = courses.stream().map(Course::getCourseTypeId).distinct().collect(Collectors.toList());
        //根据课程类别id查询类别对象
        HashMap<Integer, Category> categoryHashMapmap = new HashMap<>();
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.in(Category::getId, collectId);
        categoryLambdaQueryWrapper.eq(Category::getIsDel, false);
        List<Category> categories = categoryDao.selectList(categoryLambdaQueryWrapper);
        for (Category category : categories) {
            categoryHashMapmap.put(category.getId(), category);
        }

        //把课程id个类别对象封装到map
        for (Course cours : courses) {
            map.put(cours.getId(), categoryHashMapmap.get(cours.getCourseTypeId().intValue()));
        }
        return map;

    }

    public String getTypeName(Integer status) {
        if (status.equals(2) || status.equals(3)) {
            return "已参加";
        } else if (status.equals(1)) {
            return "未参加";
        }
        return "";
    }

    public String getTypeNameEn(Integer status) {
        if (status.equals(2) || status.equals(3)) {
            return "Have participated";
        } else if (status.equals(1)) {
            return "Not participated";
        }
        return "";
    }

}
